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

export interface ApproveBudgetInput {
  budgetId: string;
}

export async function run(db: Transaction, input: ApproveBudgetInput, ctx: CommandContext) {
  // 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));
  }

  // Segregation of duties: approver must differ from creator
  if (budget.createdByUserId === ctx.actorId) {
    return err(new SelfApprovalNotAllowedError(input.budgetId));
  }

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

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