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

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));
  }

  const nextStatus = budgetLifecycle.tryTransition(budget.status, "reject");
  if (!nextStatus) {
    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: nextStatus,
      rejectionReason: input.reason,
    })
    .where("id", "=", input.budgetId)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ budget: updated });
}
