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

export interface DeleteAccountingPeriodInput {
  id: string;
}

/**
 * Function: deleteAccountingPeriod
 *
 * Deletes an accounting period only when no journal entries reference it.
 */
export async function run(
  db: Transaction,
  input: DeleteAccountingPeriodInput,
  _ctx: CommandContext,
) {
  const period = await db
    .selectFrom("AccountingPeriod")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();

  if (!period) {
    return err(new AccountingPeriodNotFoundError(input.id));
  }

  const journalEntry = await db
    .selectFrom("JournalEntry")
    .selectAll()
    .where("accountingPeriodId", "=", input.id)
    .executeTakeFirst();

  if (journalEntry) {
    return err(new HasAssociatedJournalEntriesError(input.id));
  }

  await db.deleteFrom("AccountingPeriod").where("id", "=", input.id).executeTakeFirst();

  return ok({ deleted: true });
}
