// Auto-generated StockAlerts service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { StockAlerts, CreateStockAlertsInput, UpdateStockAlertsInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateStockAlertsInput): StockAlerts {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "product_name", "current_qty", "threshold", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.productName ?? null, input.currentQty ?? null, input.threshold ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateStockAlertsInput): StockAlerts | 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.currentQty !== undefined) { sets.push("current_qty = ?"); values.push(input.currentQty); }
    if (input.threshold !== undefined) { sets.push("threshold = ?"); values.push(input.threshold); }

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

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

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

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