// Auto-generated Schedules service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Schedules, CreateSchedulesInput, UpdateSchedulesInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateSchedulesInput): Schedules {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "course_id", "classroom_id", "instructor_id", "day_of_week", "start_time", "end_time", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.courseId ?? null, input.classroomId ?? null, input.instructorId ?? null, input.dayOfWeek ?? null, input.startTime ?? null, input.endTime ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateSchedulesInput): Schedules | 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.courseId !== undefined) { sets.push("course_id = ?"); values.push(input.courseId); }
    if (input.classroomId !== undefined) { sets.push("classroom_id = ?"); values.push(input.classroomId); }
    if (input.instructorId !== undefined) { sets.push("instructor_id = ?"); values.push(input.instructorId); }
    if (input.dayOfWeek !== undefined) { sets.push("day_of_week = ?"); values.push(input.dayOfWeek); }
    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 (sets.length === 0) return existing;

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

    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;
  }
}
