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

export interface DeleteChartOfAccountsInput {
  id: string;
}

/**
 * Function: deleteChartOfAccounts
 *
 * Permanently removes a Chart of Accounts that is still in DRAFT status.
 * Cascade-deletes all child Account and AccountGroup records belonging to the CoA.
 */
export async function run(
  db: Transaction,
  input: DeleteChartOfAccountsInput,
  _ctx: CommandContext,
) {
  const { id } = input;

  // 1. Find CoA with forUpdate
  const existing = await db
    .selectFrom("ChartOfAccounts")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!existing) {
    return err(new ChartOfAccountsNotFoundError(id));
  }

  // 2. Must be DRAFT
  if (existing.status !== "DRAFT") {
    return err(new InvalidStateTransitionError(id));
  }

  // 3. Cascade-delete all child Accounts
  await db.deleteFrom("Account").where("chartOfAccountsId", "=", id).execute();

  // 4. Cascade-delete all child AccountGroups
  await db.deleteFrom("AccountGroup").where("chartOfAccountsId", "=", id).execute();

  // 5. Delete the CoA itself
  await db.deleteFrom("ChartOfAccounts").where("id", "=", id).execute();

  return ok({ success: true as const });
}
