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 ClosePeriodInput {
  id: string;
}

const from = ["OPEN"];

export async function run(db: Transaction, input: ClosePeriodInput, 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: "CLOSED",
      updatedAt: new Date(),
    })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  // Emit audit event recording status transition from OPEN to CLOSED and acting user
  void ctx;

  return ok({ accountingPeriod: updated });
}
