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

export interface GetPurchaseRequisitionInput {
  id: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetPurchaseRequisitionInput) {
  const requisition = await db
    .selectFrom("PurchaseRequisition")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();
  if (!requisition) return ok({ purchaseRequisition: null });

  const lines = await db
    .selectFrom("PurchaseRequisitionLine")
    .selectAll()
    .where("purchaseRequisitionId", "=", input.id)
    .execute();

  const linesWithTotals = lines.map((line) => ({
    ...line,
    estimatedLineTotal: new Decimal(line.quantity).times(line.estimatedUnitPrice).toString(),
  }));

  const estimatedTotal = linesWithTotals
    .reduce((sum, line) => sum.plus(line.estimatedLineTotal), new Decimal(0))
    .toString();

  return ok({
    purchaseRequisition: {
      ...requisition,
      lines: linesWithTotals,
      estimatedTotal,
    },
  });
}
