// Auto-generated StockOut service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { StockOut, CreateStockOutInput, UpdateStockOutInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateStockOutInput): StockOut {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "product_name", "quantity", "recipient", "approved_by", "shipped_at", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.productName ?? null, input.quantity ?? null, input.recipient ?? null, input.approvedBy ?? null, input.shippedAt ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateStockOutInput): StockOut | 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.recipient !== undefined) { sets.push("recipient = ?"); values.push(input.recipient); }
    if (input.approvedBy !== undefined) { sets.push("approved_by = ?"); values.push(input.approvedBy); }
    if (input.shippedAt !== undefined) { sets.push("shipped_at = ?"); values.push(input.shippedAt); }

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

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

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

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