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

export interface PermanentlyClosePeriodInput {
  id: string;
}

const from = ["CLOSED"];

export async function run(
  db: Transaction,
  input: PermanentlyClosePeriodInput,
  ctx: CommandContext,
) {
  const period = await db
    .selectFrom("AccountingPeriod")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();

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

  if (!from.includes(period.status as string)) {
    return err(new InvalidStatusTransitionError(input.id));
  }

  const updated = await db
    .updateTable("AccountingPeriod")
    .set({
      status: "PERMANENTLY_CLOSED",
      updatedAt: new Date(),
    })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  // Emit audit event recording the irreversible transition and acting user
  void ctx;

  return ok({ accountingPeriod: updated });
}
