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

export interface RejectPurchaseOrderInput {
  id: string;
  reason: string;
}

export async function run(db: Transaction, input: RejectPurchaseOrderInput, ctx: CommandContext) {
  void ctx;
  const purchaseOrder = await selectOne(db, "PurchaseOrder", "id", input.id, true);
  if (!purchaseOrder) {
    return err(new PurchaseOrderNotFoundError(input.id));
  }
  if (purchaseOrder.status !== "SUBMITTED") {
    return err(new PurchaseOrderNotSubmittedError(input.id));
  }
  if (!input.reason.trim()) {
    return err(new RejectionReasonRequiredError(input.id));
  }

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

  return ok({ purchaseOrder: rejected });
}
