import type { Transaction } from "../generated/kysely-tailordb";
import type { defineModule as defineBusinessPartnerModule } from "../../business-partner";
type BusinessPartnerModule = ReturnType<typeof defineBusinessPartnerModule>;
type BusinessPartnerQueries = BusinessPartnerModule["queries"];
import {
  DuplicateExternalSupplierOrderReferenceError,
  EmptyPurchaseOrderLinesError,
  PartnerNotSupplierError,
  PurchaseOrderNotDraftError,
  PurchaseOrderNotFoundError,
  ReceivingSiteRequiredError,
} from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";

export interface SubmitPurchaseOrderInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: SubmitPurchaseOrderInput,
  ctx: CommandContext,
  businessPartnerQueries: Pick<BusinessPartnerQueries, "getPartnerRole">,
) {
  const purchaseOrder = await db
    .selectFrom("PurchaseOrder")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!purchaseOrder) {
    return err(new PurchaseOrderNotFoundError(input.id));
  }
  if (purchaseOrder.orderStatus !== "DRAFT") {
    return err(new PurchaseOrderNotDraftError(input.id));
  }

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

  if (lines.length === 0) {
    return err(new EmptyPurchaseOrderLinesError(input.id));
  }
  for (const line of lines) {
    if ((line.requiresPhysicalReceipt ?? true) && !line.receivingSiteId) {
      return err(new ReceivingSiteRequiredError(line.itemId));
    }
  }
  const { partnerRole } = (
    await businessPartnerQueries.getPartnerRole(
      db,
      { partnerId: purchaseOrder.supplierId, role: "SUPPLIER" },
      ctx,
    )
  ).value;
  if (!partnerRole) {
    return err(new PartnerNotSupplierError(purchaseOrder.supplierId));
  }
  if (purchaseOrder.externalSupplierOrderReference) {
    const duplicate = await db
      .selectFrom("PurchaseOrder")
      .selectAll()
      .where("companyId", "=", purchaseOrder.companyId)
      .where("externalSupplierOrderReference", "=", purchaseOrder.externalSupplierOrderReference)
      .executeTakeFirst();
    if (duplicate && duplicate.id !== input.id) {
      return err(
        new DuplicateExternalSupplierOrderReferenceError(
          purchaseOrder.externalSupplierOrderReference,
        ),
      );
    }
  }

  const submitted = await db
    .updateTable("PurchaseOrder")
    .set({ orderStatus: "SUBMITTED", updatedAt: new Date() })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchaseOrder: submitted });
}
