/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */
import type { Transaction } from "../generated/kysely-tailordb";
import {
  PurchaseOrderAlreadyFulfilledError,
  PurchaseOrderNotCancellableError,
  PurchaseOrderNotFoundError,
} from "../lib/errors.generated";
import {
  decodeJson,
  selectOne,
  type PurchaseBillLineInput,
  type PurchaseOrderLineInput,
} from "../lib/domain";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface CancelPurchaseOrderInput {
  id: string;
}

export async function run(db: Transaction, input: CancelPurchaseOrderInput, ctx: CommandContext) {
  void ctx;
  const purchaseOrder = await selectOne(db, "PurchaseOrder", "id", input.id, true);
  if (!purchaseOrder) {
    return err(new PurchaseOrderNotFoundError(input.id));
  }
  if (!["DRAFT", "SUBMITTED", "ORDERED"].includes(purchaseOrder.status as string)) {
    return err(new PurchaseOrderNotCancellableError(input.id));
  }

  const postedReceipt = await db
    .selectFrom("GoodsReceipt")
    .selectAll()
    .where("purchaseOrderId", "=", input.id)
    .where("status", "=", "POSTED")
    .executeTakeFirst();
  if (postedReceipt) {
    return err(new PurchaseOrderAlreadyFulfilledError(input.id));
  }

  const purchaseOrderLineIds = new Set(
    decodeJson<PurchaseOrderLineInput[]>(purchaseOrder.lines, []).map((line) => line.id),
  );
  const matchedBills = await db
    .selectFrom("PurchaseBill")
    .selectAll()
    .where("status", "=", "MATCHED")
    .execute();
  const matchedBill = matchedBills.find((bill) =>
    decodeJson<PurchaseBillLineInput[]>(bill.lines, []).some((line) =>
      purchaseOrderLineIds.has(line.purchaseOrderLineId),
    ),
  );
  if (matchedBill) {
    return err(new PurchaseOrderAlreadyFulfilledError(input.id));
  }

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

  return ok({ purchaseOrder: cancelled });
}
