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

export interface ActivateBudgetInput {
  budgetId: string;
}

export async function run(db: Transaction, input: ActivateBudgetInput, 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 !== "APPROVED") {
    return err(new InvalidStateError(input.budgetId));
  }

  // Check plan version type — only BUDGET type needs uniqueness check
  const planVersion = await db
    .selectFrom("PlanVersion")
    .where("id", "=", budget.planVersionId)
    .selectAll()
    .executeTakeFirst();

  if (planVersion?.type === "BUDGET") {
    // Check no other ACTIVE budget of type BUDGET exists for same cost object and fiscal year
    const existingActive = await db
      .selectFrom("Budget")
      .where("costObjectType", "=", budget.costObjectType)
      .where("costObjectId", "=", budget.costObjectId)
      .where("fiscalYearId", "=", budget.fiscalYearId)
      .where("status", "=", "ACTIVE")
      .where("id", "!=", input.budgetId)
      .selectAll()
      .executeTakeFirst();

    if (existingActive) {
      // Verify the existing active budget is also of type BUDGET
      const existingPlanVersion = await db
        .selectFrom("PlanVersion")
        .where("id", "=", existingActive.planVersionId)
        .selectAll()
        .executeTakeFirst();

      if (existingPlanVersion?.type === "BUDGET") {
        return err(new DuplicateActiveBudgetError(input.budgetId));
      }
    }
  }

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

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