// Auto-generated Assets service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Assets, CreateAssetsInput, UpdateAssetsInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateAssetsInput): Assets {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "name", "category", "purchase_date", "purchase_price", "current_value", "location", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.name ?? null, input.category ?? null, input.purchaseDate ?? null, input.purchasePrice ?? null, input.currentValue ?? null, input.location ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateAssetsInput): Assets | 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.category !== undefined) { sets.push("category = ?"); values.push(input.category); }
    if (input.purchaseDate !== undefined) { sets.push("purchase_date = ?"); values.push(input.purchaseDate); }
    if (input.purchasePrice !== undefined) { sets.push("purchase_price = ?"); values.push(input.purchasePrice); }
    if (input.currentValue !== undefined) { sets.push("current_value = ?"); values.push(input.currentValue); }
    if (input.location !== undefined) { sets.push("location = ?"); values.push(input.location); }

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

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

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

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