// Auto-generated Inventory service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Inventory, CreateInventoryInput, UpdateInventoryInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateInventoryInput): Inventory {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const hasCreatedAt = true;
    const hasUpdatedAt = true;
    const cols = ["id", "user_id", "product_id", "quantity", "warehouse", "min_stock", "max_stock", "created_at", "updated_at"];
    const placeholders = cols.map(() => "?").join(", ");
    const values = [id, input.userId ?? null, input.productId ?? null, input.quantity ?? null, input.warehouse ?? null, input.minStock ?? null, input.maxStock ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateInventoryInput): Inventory | 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.productId !== undefined) { sets.push("product_id = ?"); values.push(input.productId); }
    if (input.quantity !== undefined) { sets.push("quantity = ?"); values.push(input.quantity); }
    if (input.warehouse !== undefined) { sets.push("warehouse = ?"); values.push(input.warehouse); }
    if (input.minStock !== undefined) { sets.push("min_stock = ?"); values.push(input.minStock); }
    if (input.maxStock !== undefined) { sets.push("max_stock = ?"); values.push(input.maxStock); }

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

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

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

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