// Auto-generated Exercis service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Exercis, CreateExercisInput, UpdateExercisInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateExercisInput): Exercis {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const hasCreatedAt = false;
    const hasUpdatedAt = false;
    const cols = ["id", "lesson_id", "question", "options", "answer"];
    const placeholders = cols.map(() => "?").join(", ");
    const values = [id, input.lessonId ?? null, input.question ?? null, input.options ?? null, input.answer ?? null];

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

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

    const sets: string[] = [];
    const values: unknown[] = [];
    if (input.lessonId !== undefined) { sets.push("lesson_id = ?"); values.push(input.lessonId); }
    if (input.question !== undefined) { sets.push("question = ?"); values.push(input.question); }
    if (input.options !== undefined) { sets.push("options = ?"); values.push(input.options); }
    if (input.answer !== undefined) { sets.push("answer = ?"); values.push(input.answer); }

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

    

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

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