// Auto-generated Courses service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Courses, CreateCoursesInput, UpdateCoursesInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateCoursesInput): Courses {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "title", "description", "instructor", "price", "cover_url", "category", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.title ?? null, input.description ?? null, input.instructor ?? null, input.price ?? null, input.coverUrl ?? null, input.category ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateCoursesInput): Courses | 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.title !== undefined) { sets.push("title = ?"); values.push(input.title); }
    if (input.description !== undefined) { sets.push("description = ?"); values.push(input.description); }
    if (input.instructor !== undefined) { sets.push("instructor = ?"); values.push(input.instructor); }
    if (input.price !== undefined) { sets.push("price = ?"); values.push(input.price); }
    if (input.coverUrl !== undefined) { sets.push("cover_url = ?"); values.push(input.coverUrl); }
    if (input.category !== undefined) { sets.push("category = ?"); values.push(input.category); }

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

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

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

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