import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import type { DB } from "../generated/kysely-tailordb";

export type GetPurchaseBillInput =
  | { id: string }
  | { companyId: string; supplierId: string; invoiceNumber: string };

export async function run(db: ReadonlyDB<DB>, input: GetPurchaseBillInput) {
  let id: string;
  if ("id" in input) {
    id = input.id;
  } else {
    const purchaseBill = await db
      .selectFrom("PurchaseBill")
      .selectAll()
      .where("companyId", "=", input.companyId)
      .where("supplierId", "=", input.supplierId)
      .where("invoiceNumber", "=", input.invoiceNumber)
      .executeTakeFirst();
    if (!purchaseBill) return ok({ purchaseBill: null });
    id = purchaseBill.id;
  }

  const purchaseBill = await db
    .selectFrom("PurchaseBill")
    .selectAll()
    .where("id", "=", id)
    .executeTakeFirst();
  if (!purchaseBill) return ok({ purchaseBill: null });

  const lines = await db
    .selectFrom("PurchaseBillLine")
    .selectAll()
    .where("purchaseBillId", "=", id)
    .execute();

  return ok({
    purchaseBill: {
      ...purchaseBill,
      lines,
    },
  });
}
