// Auto-generated Appointments service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Appointments, CreateAppointmentsInput, UpdateAppointmentsInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateAppointmentsInput): Appointments {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "client_id", "service_id", "start_time", "end_time", "notes", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.clientId ?? null, input.serviceId ?? null, input.startTime ?? null, input.endTime ?? null, input.notes ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateAppointmentsInput): Appointments | 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.clientId !== undefined) { sets.push("client_id = ?"); values.push(input.clientId); }
    if (input.serviceId !== undefined) { sets.push("service_id = ?"); values.push(input.serviceId); }
    if (input.startTime !== undefined) { sets.push("start_time = ?"); values.push(input.startTime); }
    if (input.endTime !== undefined) { sets.push("end_time = ?"); values.push(input.endTime); }
    if (input.notes !== undefined) { sets.push("notes = ?"); values.push(input.notes); }

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

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

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

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