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

export interface DeleteBudgetLineItemInput {
  budgetLineItemId: string;
}

export async function run(db: Transaction, input: DeleteBudgetLineItemInput, ctx: CommandContext) {
  void ctx;

  // Fetch the line item
  const lineItem = await db
    .selectFrom("BudgetLineItem")
    .where("id", "=", input.budgetLineItemId)
    .selectAll()
    .forUpdate()
    .executeTakeFirst();

  if (!lineItem) {
    return err(new BudgetLineItemNotFoundError(input.budgetLineItemId));
  }

  // Fetch parent budget
  const budget = await db
    .selectFrom("Budget")
    .where("id", "=", lineItem.budgetId)
    .selectAll()
    .forUpdate()
    .executeTakeFirst();

  if (budget?.status !== "DRAFT") {
    return err(new InvalidStateError(lineItem.budgetId));
  }

  // Delete line item
  await db.deleteFrom("BudgetLineItem").where("id", "=", input.budgetLineItemId).execute();

  // Update budget totalAmount
  await db
    .updateTable("Budget")
    .set({
      totalAmount: budget.totalAmount - lineItem.plannedAmount,
      updatedAt: new Date(),
    })
    .where("id", "=", lineItem.budgetId)
    .execute();

  return ok({ budgetLineItemId: input.budgetLineItemId });
}
