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

export interface RejectSalesOrderInput {
  salesOrderId: string;
  rejectionReason: string;
}

export async function run(db: Transaction, input: RejectSalesOrderInput, 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 (salesOrder.status !== "SUBMITTED") {
    return err(new InvalidOrderStatusError(input.salesOrderId));
  }
  if (!input.rejectionReason.trim()) {
    return err(new RejectionReasonRequiredError(input.salesOrderId));
  }
  const updated = await db
    .updateTable("SalesOrder")
    .set({
      status: "DRAFT",
      rejectionReason: input.rejectionReason,
      updatedAt: new Date(),
    })
    .where("id", "=", input.salesOrderId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesOrder: updated! });
}
