import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { Decimal } from "decimal.js";
import { purchaseRequisitionLifecycle } from "../db/purchaseRequisition.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  DescriptionRequiredError,
  EmptyPurchaseRequisitionLinesError,
  InvalidEstimatedUnitPriceError,
  InvalidQuantityError,
  PurchaseRequisitionNotDraftError,
  PurchaseRequisitionNotFoundError,
} from "../lib/errors.generated";

export interface SubmitPurchaseRequisitionInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: SubmitPurchaseRequisitionInput,
  ctx: CommandContext,
) {
  void ctx;

  const purchaseRequisition = await db
    .selectFrom("PurchaseRequisition")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!purchaseRequisition) {
    return err(new PurchaseRequisitionNotFoundError(input.id));
  }
  const nextStatus = purchaseRequisitionLifecycle.tryTransition(
    purchaseRequisition.status,
    "submit",
  );
  if (!nextStatus) {
    return err(new PurchaseRequisitionNotDraftError(input.id));
  }

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

  if (lines.length === 0) {
    return err(new EmptyPurchaseRequisitionLinesError(input.id));
  }

  for (const line of lines) {
    if (!line.description) {
      return err(new DescriptionRequiredError(line.id));
    }
    if (new Decimal(line.quantity).lte(0)) {
      return err(new InvalidQuantityError(line.id));
    }
    if (new Decimal(line.estimatedUnitPrice).lt(0)) {
      return err(new InvalidEstimatedUnitPriceError(line.id));
    }
  }

  const submitted = await db
    .updateTable("PurchaseRequisition")
    .set({ status: nextStatus })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchaseRequisition: submitted });
}
