// Auto-generated Stocktaking service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Stocktaking, CreateStocktakingInput, UpdateStocktakingInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateStocktakingInput): Stocktaking {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "warehouse", "product_name", "expected_qty", "actual_qty", "diff", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.warehouse ?? null, input.productName ?? null, input.expectedQty ?? null, input.actualQty ?? null, input.diff ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateStocktakingInput): Stocktaking | 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.warehouse !== undefined) { sets.push("warehouse = ?"); values.push(input.warehouse); }
    if (input.productName !== undefined) { sets.push("product_name = ?"); values.push(input.productName); }
    if (input.expectedQty !== undefined) { sets.push("expected_qty = ?"); values.push(input.expectedQty); }
    if (input.actualQty !== undefined) { sets.push("actual_qty = ?"); values.push(input.actualQty); }
    if (input.diff !== undefined) { sets.push("diff = ?"); values.push(input.diff); }

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

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

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

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