// Auto-generated Hospitals service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Hospitals, CreateHospitalsInput, UpdateHospitalsInput } from "../types/index.js";

export class HospitalsService {
  /** List all hospitals */
  list(): Hospitals[] {
    return queryAll<Hospitals>("SELECT * FROM hospitals ORDER BY created_at DESC");
  }

  /** Get by ID */
  getById(id: string): Hospitals | undefined {
    return queryOne<Hospitals>("SELECT * FROM hospitals WHERE id = ?", [id]);
  }

  /** Create */
  create(input: CreateHospitalsInput): Hospitals {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "name", "address", "phone", "rating", "lat", "lng", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.name ?? null, input.address ?? null, input.phone ?? null, input.rating ?? null, input.lat ?? null, input.lng ?? null, now, now];

    execute(`INSERT INTO hospitals (${cols.join(", ")}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, values);
    return this.getById(id)!;
  }

  /** Update */
  update(id: string, input: UpdateHospitalsInput): Hospitals | undefined {
    const existing = this.getById(id);
    if (!existing) return undefined;

    const sets: string[] = [];
    const values: unknown[] = [];
    if (input.userId !== undefined) { sets.push("user_id = ?"); values.push(input.userId); }
    if (input.name !== undefined) { sets.push("name = ?"); values.push(input.name); }
    if (input.address !== undefined) { sets.push("address = ?"); values.push(input.address); }
    if (input.phone !== undefined) { sets.push("phone = ?"); values.push(input.phone); }
    if (input.rating !== undefined) { sets.push("rating = ?"); values.push(input.rating); }
    if (input.lat !== undefined) { sets.push("lat = ?"); values.push(input.lat); }
    if (input.lng !== undefined) { sets.push("lng = ?"); values.push(input.lng); }

    if (sets.length === 0) return existing;

    sets.push("updated_at = ?");
    values.push(new Date().toISOString());

    values.push(id);
    execute(`UPDATE hospitals SET ${sets.join(", ")} WHERE id = ?`, values);
    return this.getById(id)!;
  }

  /** Delete */
  delete(id: string): boolean {
    const result = execute("DELETE FROM hospitals WHERE id = ?", [id]);
    return result.changes > 0;
  }
}
