// Auto-generated SalesPipeline service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { SalesPipeline, CreateSalesPipelineInput, UpdateSalesPipelineInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateSalesPipelineInput): SalesPipeline {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "customer_id", "stage", "amount", "probability", "expected_close", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.customerId ?? null, input.stage ?? null, input.amount ?? null, input.probability ?? null, input.expectedClose ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateSalesPipelineInput): SalesPipeline | 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.customerId !== undefined) { sets.push("customer_id = ?"); values.push(input.customerId); }
    if (input.stage !== undefined) { sets.push("stage = ?"); values.push(input.stage); }
    if (input.amount !== undefined) { sets.push("amount = ?"); values.push(input.amount); }
    if (input.probability !== undefined) { sets.push("probability = ?"); values.push(input.probability); }
    if (input.expectedClose !== undefined) { sets.push("expected_close = ?"); values.push(input.expectedClose); }

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

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

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

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