// Auto-generated Item service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Item, CreateItemInput, UpdateItemInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateItemInput): Item {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const hasCreatedAt = true;
    const hasUpdatedAt = false;
    const cols = ["id", "user_id", "title", "data", "created_at"];
    const placeholders = cols.map(() => "?").join(", ");
    const values = [id, input.userId ?? null, input.title ?? null, input.data ?? null, now];

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

  /** Update */
  update(id: string, input: UpdateItemInput): Item | 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.data !== undefined) { sets.push("data = ?"); values.push(input.data); }

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

    

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

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