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

export interface DeleteAccountGroupInput {
  id: string;
}

/**
 * Function: deleteAccountGroup
 *
 * Permanently removes an account group that has no child groups and no assigned
 * accounts.
 */
export async function run(db: Transaction, input: DeleteAccountGroupInput, _ctx: CommandContext) {
  const { id } = input;

  // 1. Find the group
  const existing = await db
    .selectFrom("AccountGroup")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

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

  // 2. Check parent CoA status
  const coa = await db
    .selectFrom("ChartOfAccounts")
    .selectAll()
    .where("id", "=", existing.chartOfAccountsId)
    .executeTakeFirst();

  if (coa!.status === "ARCHIVED") {
    return err(new ChartOfAccountsArchivedError(existing.chartOfAccountsId));
  }

  // 3. Check for child groups
  const childGroups = await db
    .selectFrom("AccountGroup")
    .selectAll()
    .where("parentAccountGroupId", "=", id)
    .execute();

  if (childGroups.length > 0) {
    return err(new HasChildGroupsError(id));
  }

  // 4. Check for assigned accounts
  const assignedAccounts = await db
    .selectFrom("Account")
    .selectAll()
    .where("accountGroupId", "=", id)
    .execute();

  if (assignedAccounts.length > 0) {
    return err(new HasAssignedAccountsError(id));
  }

  // 5. Delete the group
  await db.deleteFrom("AccountGroup").where("id", "=", id).execute();

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