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

export interface DeleteFiscalYearInput {
  id: string;
}

/**
 * Function: deleteFiscalYear
 *
 * Deletes a fiscal year only when no accounting periods reference it.
 */
export async function run(db: Transaction, input: DeleteFiscalYearInput, _ctx: CommandContext) {
  const fiscalYear = await db
    .selectFrom("FiscalYear")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();

  if (!fiscalYear) {
    return err(new FiscalYearNotFoundError(input.id));
  }

  const period = await db
    .selectFrom("AccountingPeriod")
    .selectAll()
    .where("fiscalYearId", "=", input.id)
    .executeTakeFirst();

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

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

  return ok({ deleted: true });
}
