import type { Transaction } from "../generated/kysely-tailordb";
import {
  HoldReasonRequiredError,
  InvalidOrderStatusError,
  SalesOrderNotFoundError,
} from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface PlaceSalesOrderOnCreditHoldInput {
  salesOrderId: string;
  holdReason: string;
}

export async function run(
  db: Transaction,
  input: PlaceSalesOrderOnCreditHoldInput,
  ctx: CommandContext,
) {
  void ctx;
  const salesOrder = await db
    .selectFrom("SalesOrder")
    .selectAll()
    .where("id", "=", input.salesOrderId)
    .forUpdate()
    .executeTakeFirst();
  if (!salesOrder) {
    return err(new SalesOrderNotFoundError(input.salesOrderId));
  }
  if (
    !["CONFIRMED", "PARTIALLY_SHIPPED", "PARTIALLY_INVOICED", "SHIPPED", "INVOICED"].includes(
      salesOrder.status,
    )
  ) {
    return err(new InvalidOrderStatusError(input.salesOrderId));
  }
  if (!input.holdReason.trim()) {
    return err(new HoldReasonRequiredError(input.salesOrderId));
  }
  const updated = await db
    .updateTable("SalesOrder")
    .set({ status: "CREDIT_HOLD", holdReason: input.holdReason, updatedAt: new Date() })
    .where("id", "=", input.salesOrderId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesOrder: updated! });
}
