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

export interface ClosePurchaseOrderInput {
  id: string;
  closeReason?: string;
  writeOffRemaining?: boolean;
}

export async function run(db: Transaction, input: ClosePurchaseOrderInput, ctx: CommandContext) {
  void ctx;
  const purchaseOrder = await selectOne(db, "PurchaseOrder", "id", input.id, true);
  if (!purchaseOrder) {
    return err(new PurchaseOrderNotFoundError(input.id));
  }
  if (
    !["PARTIALLY_RECEIVED", "RECEIVED", "PARTIALLY_BILLED", "BILLED"].includes(
      purchaseOrder.status as string,
    )
  ) {
    return err(new PurchaseOrderNotClosableError(input.id));
  }

  const lines = decodeJson<PurchaseOrderLineInput[]>(purchaseOrder.lines, []);
  const hasUnresolvedOpenQuantity = lines.some(
    (line) =>
      (line.receivedQuantity ?? 0) < line.quantity && (line.billedQuantity ?? 0) < line.quantity,
  );
  const writeOffRequested = input.writeOffRemaining === true;

  if (hasUnresolvedOpenQuantity && !writeOffRequested) {
    return err(new OpenQuantityRemainsError(input.id));
  }
  if (hasUnresolvedOpenQuantity && writeOffRequested && !input.closeReason?.trim()) {
    return err(new CloseReasonRequiredError(input.id));
  }

  const closed = await db
    .updateTable("PurchaseOrder")
    .set({
      status: "CLOSED",
      closeReason: input.closeReason ?? null,
      updatedAt: new Date(),
    })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchaseOrder: closed });
}
