// Auto-generated Suppliers service
import { queryAll, queryOne, execute } from "../db/client.js";
import type { Suppliers, CreateSuppliersInput, UpdateSuppliersInput } from "../types/index.js";

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

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

  /** Create */
  create(input: CreateSuppliersInput): Suppliers {
    const id = crypto.randomUUID();
    const now = new Date().toISOString();
    const cols = ["id", "user_id", "name", "contact", "phone", "email", "address", "created_at", "updated_at"];
    const values = [id, input.userId ?? null, input.name ?? null, input.contact ?? null, input.phone ?? null, input.email ?? null, input.address ?? null, now, now];

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

  /** Update */
  update(id: string, input: UpdateSuppliersInput): Suppliers | 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.name !== undefined) { sets.push("name = ?"); values.push(input.name); }
    if (input.contact !== undefined) { sets.push("contact = ?"); values.push(input.contact); }
    if (input.phone !== undefined) { sets.push("phone = ?"); values.push(input.phone); }
    if (input.email !== undefined) { sets.push("email = ?"); values.push(input.email); }
    if (input.address !== undefined) { sets.push("address = ?"); values.push(input.address); }

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

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

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

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