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

export interface DeleteAccountingPeriodInput {
  id: string;
}

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

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

  if (periodClose) {
    return err(new HasActivePeriodCloseError(input.id));
  }

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

  // Emit audit event recording acting user, timestamp, and deleted period details
  void ctx;

  return ok({ deleted: true });
}
