import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { purchaseOrderLifecycle } from "../db/purchaseOrder.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  PurchaseOrderAlreadyFulfilledError,
  PurchaseOrderNotCancellableError,
  PurchaseOrderNotFoundError,
} from "../lib/errors.generated";

export interface CancelPurchaseOrderInput {
  id: string;
}

export async function run(db: Transaction, input: CancelPurchaseOrderInput, ctx: CommandContext) {
  void ctx;
  const purchaseOrder = await db
    .selectFrom("PurchaseOrder")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!purchaseOrder) {
    return err(new PurchaseOrderNotFoundError(input.id));
  }
  const nextOrderStatus = purchaseOrderLifecycle.tryTransition(purchaseOrder.orderStatus, "cancel");
  if (!nextOrderStatus) {
    return err(new PurchaseOrderNotCancellableError(input.id));
  }

  const purchaseOrderLines = await db
    .selectFrom("PurchaseOrderLine")
    .selectAll()
    .where("purchaseOrderId", "=", input.id)
    .execute();
  const purchaseOrderLineIds = new Set(purchaseOrderLines.map((line) => line.id));

  if (purchaseOrderLineIds.size > 0) {
    // Check for posted receipts via receipt lines referencing this PO's lines
    const postedReceiptLine = await db
      .selectFrom("GoodsReceiptLine")
      .innerJoin("GoodsReceipt", "GoodsReceipt.id", "GoodsReceiptLine.goodsReceiptId")
      .selectAll("GoodsReceiptLine")
      .where("GoodsReceiptLine.purchaseOrderLineId", "in", [...purchaseOrderLineIds])
      .where("GoodsReceipt.status", "=", "POSTED")
      .executeTakeFirst();
    if (postedReceiptLine) {
      return err(new PurchaseOrderAlreadyFulfilledError(input.id));
    }

    // Check for matched bill lines referencing this PO's lines
    const matchedBillLine = await db
      .selectFrom("PurchaseBillLine")
      .innerJoin("PurchaseBill", "PurchaseBill.id", "PurchaseBillLine.purchaseBillId")
      .selectAll("PurchaseBillLine")
      .where("PurchaseBillLine.purchaseOrderLineId", "in", [...purchaseOrderLineIds])
      .where("PurchaseBill.status", "=", "MATCHED")
      .executeTakeFirst();
    if (matchedBillLine) {
      return err(new PurchaseOrderAlreadyFulfilledError(input.id));
    }
  }

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

  return ok({ purchaseOrder: cancelled });
}
