// Auto-generated Lesson service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Lesson, CreateLessonInput, UpdateLessonInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateLessonInput): Lesson {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const hasCreatedAt = false;
    const hasUpdatedAt = false;
    const cols = ["id", "course_id", "title", "video_url", "duration_sec", "sort_order"];
    const placeholders = cols.map(() => "?").join(", ");
    const values = [id, input.courseId ?? null, input.title ?? null, input.videoUrl ?? null, input.durationSec ?? null, input.sortOrder ?? null];

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

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

    const sets: string[] = [];
    const values: unknown[] = [];
    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.videoUrl !== undefined) { sets.push("video_url = ?"); values.push(input.videoUrl); }
    if (input.durationSec !== undefined) { sets.push("duration_sec = ?"); values.push(input.durationSec); }
    if (input.sortOrder !== undefined) { sets.push("sort_order = ?"); values.push(input.sortOrder); }

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

    

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

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