// Auto-generated Albums service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Albums, CreateAlbumsInput, UpdateAlbumsInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateAlbumsInput): Albums {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "title", "image_url", "caption", "taken_at", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.title ?? null, input.imageUrl ?? null, input.caption ?? null, input.takenAt ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateAlbumsInput): Albums | 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.imageUrl !== undefined) { sets.push("image_url = ?"); values.push(input.imageUrl); }
    if (input.caption !== undefined) { sets.push("caption = ?"); values.push(input.caption); }
    if (input.takenAt !== undefined) { sets.push("taken_at = ?"); values.push(input.takenAt); }

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

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

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

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