// Auto-generated Equipment service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Equipment, CreateEquipmentInput, UpdateEquipmentInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateEquipmentInput): Equipment {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "name", "code", "location", "model", "installed_at", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.name ?? null, input.code ?? null, input.location ?? null, input.model ?? null, input.installedAt ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateEquipmentInput): Equipment | 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.name !== undefined) { sets.push("name = ?"); values.push(input.name); }
    if (input.code !== undefined) { sets.push("code = ?"); values.push(input.code); }
    if (input.location !== undefined) { sets.push("location = ?"); values.push(input.location); }
    if (input.model !== undefined) { sets.push("model = ?"); values.push(input.model); }
    if (input.installedAt !== undefined) { sets.push("installed_at = ?"); values.push(input.installedAt); }

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

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

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

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