// Auto-generated Schedule service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Schedule, CreateScheduleInput, UpdateScheduleInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateScheduleInput): Schedule {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const hasCreatedAt = false;
    const hasUpdatedAt = false;
    const cols = ["id", "pet_id", "type", "title", "scheduled_at", "completed"];
    const placeholders = cols.map(() => "?").join(", ");
    const values = [id, input.petId ?? null, input.type ?? null, input.title ?? null, input.scheduledAt ?? null, input.completed ?? null];

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

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

    const sets: string[] = [];
    const values: unknown[] = [];
    if (input.petId !== undefined) { sets.push("pet_id = ?"); values.push(input.petId); }
    if (input.type !== undefined) { sets.push("type = ?"); values.push(input.type); }
    if (input.title !== undefined) { sets.push("title = ?"); values.push(input.title); }
    if (input.scheduledAt !== undefined) { sets.push("scheduled_at = ?"); values.push(input.scheduledAt); }
    if (input.completed !== undefined) { sets.push("completed = ?"); values.push(input.completed); }

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

    

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

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