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

const from = ["CLOSED"];

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

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

  return ok({ accountingPeriod: updated });
}
