// Auto-generated Media service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Media, CreateMediaInput, UpdateMediaInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateMediaInput): Media {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "filename", "url", "mime_type", "size_bytes", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.filename ?? null, input.url ?? null, input.mimeType ?? null, input.sizeBytes ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateMediaInput): Media | 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.filename !== undefined) { sets.push("filename = ?"); values.push(input.filename); }
    if (input.url !== undefined) { sets.push("url = ?"); values.push(input.url); }
    if (input.mimeType !== undefined) { sets.push("mime_type = ?"); values.push(input.mimeType); }
    if (input.sizeBytes !== undefined) { sets.push("size_bytes = ?"); values.push(input.sizeBytes); }

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

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

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

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