// Auto-generated UserProgress service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { UserProgress, CreateUserProgressInput, UpdateUserProgressInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateUserProgressInput): UserProgress {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const hasCreatedAt = false;
    const hasUpdatedAt = false;
    const cols = ["id", "user_id", "lesson_id", "completed", "watched_sec"];
    const placeholders = cols.map(() => "?").join(", ");
    const values = [id, input.userId ?? null, input.lessonId ?? null, input.completed ?? null, input.watchedSec ?? null];

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

  /** Update */
  update(id: string, input: UpdateUserProgressInput): UserProgress | 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.lessonId !== undefined) { sets.push("lesson_id = ?"); values.push(input.lessonId); }
    if (input.completed !== undefined) { sets.push("completed = ?"); values.push(input.completed); }
    if (input.watchedSec !== undefined) { sets.push("watched_sec = ?"); values.push(input.watchedSec); }

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

    

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

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