// Auto-generated Chapters service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Chapters, CreateChaptersInput, UpdateChaptersInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateChaptersInput): Chapters {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "course_id", "title", "duration_min", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.courseId ?? null, input.title ?? null, input.durationMin ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateChaptersInput): Chapters | 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.title !== undefined) { sets.push("title = ?"); values.push(input.title); }
    if (input.durationMin !== undefined) { sets.push("duration_min = ?"); values.push(input.durationMin); }

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

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

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

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