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, NoLineItemsError } from "../lib/errors.generated";

export interface SubmitBudgetInput {
  budgetId: string;
}

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

  // Check at least one line item exists
  const lineItem = await db
    .selectFrom("BudgetLineItem")
    .where("budgetId", "=", input.budgetId)
    .selectAll()
    .executeTakeFirst();

  if (!lineItem) {
    return err(new NoLineItemsError(input.budgetId));
  }

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

  return ok({ budget: updated });
}
