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

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

  if (budget.status !== "DRAFT") {
    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: "SUBMITTED",
      updatedAt: new Date(),
    })
    .where("id", "=", input.budgetId)
    .returningAll()
    .executeTakeFirst();

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