// Auto-generated Warehouse service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Warehouse, CreateWarehouseInput, UpdateWarehouseInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateWarehouseInput): Warehouse {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "product_name", "quantity", "supplier", "received_by", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.productName ?? null, input.quantity ?? null, input.supplier ?? null, input.receivedBy ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateWarehouseInput): Warehouse | 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.productName !== undefined) { sets.push("product_name = ?"); values.push(input.productName); }
    if (input.quantity !== undefined) { sets.push("quantity = ?"); values.push(input.quantity); }
    if (input.supplier !== undefined) { sets.push("supplier = ?"); values.push(input.supplier); }
    if (input.receivedBy !== undefined) { sets.push("received_by = ?"); values.push(input.receivedBy); }

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

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

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

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