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

export type GetPurchaseChangeOrderInput = { id: string } | { purchaseOrderId: string };

export async function run(db: ReadonlyDB<DB>, input: GetPurchaseChangeOrderInput) {
  let purchaseChangeOrder;

  if ("id" in input) {
    purchaseChangeOrder = await db
      .selectFrom("PurchaseChangeOrder")
      .selectAll()
      .where("id", "=", input.id)
      .executeTakeFirst();
  } else {
    purchaseChangeOrder = await db
      .selectFrom("PurchaseChangeOrder")
      .selectAll()
      .where("purchaseOrderId", "=", input.purchaseOrderId)
      .where("changeOrderStatus", "in", ["DRAFT", "SUBMITTED", "APPROVED"])
      .executeTakeFirst();
  }

  if (!purchaseChangeOrder) return ok({ purchaseChangeOrder: null });

  const lines = await db
    .selectFrom("PurchaseChangeOrderLine")
    .selectAll()
    .where("purchaseChangeOrderId", "=", purchaseChangeOrder.id)
    .execute();

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