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

export interface RejectBudgetInput {
  budgetId: string;
  reason: string;
}

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

  // Fetch budget with lock
  const budget = await db
    .selectFrom("Budget")
    .where("id", "=", input.budgetId)
    .selectAll()
    .forUpdate()
    .executeTakeFirst();

  if (!budget) {
    return err(new BudgetNotFoundError(input.budgetId));
  }

  if (budget.status !== "SUBMITTED") {
    return err(new InvalidStateError(input.budgetId));
  }

  // Validate reason is provided
  if (!input.reason || input.reason.trim() === "") {
    return err(new ReasonRequiredError(input.budgetId));
  }

  // Transition back to DRAFT
  const updated = await db
    .updateTable("Budget")
    .set({
      status: "DRAFT",
      rejectionReason: input.reason,
      updatedAt: new Date(),
    })
    .where("id", "=", input.budgetId)
    .returningAll()
    .executeTakeFirst();

  return ok({ budget: updated! });
}
