import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { allocationCycleLifecycle } from "../db/allocationCycle.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { createAllocationReversalEntries } from "../lib/allocationPosting";
import {
  AllocationCycleNotFoundError,
  InvalidStateError,
  PeriodNotOpenError,
} from "../lib/errors.generated";

export interface ReverseAllocationCycleInput {
  allocationCycleId: string;
}

export async function run(
  db: Transaction,
  input: ReverseAllocationCycleInput,
  ctx: CommandContext,
) {
  void ctx;

  // Validate allocation cycle exists
  const cycle = await db
    .selectFrom("AllocationCycle")
    .where("id", "=", input.allocationCycleId)
    .selectAll()
    .forUpdate()
    .executeTakeFirst();

  if (!cycle) {
    return err(new AllocationCycleNotFoundError(input.allocationCycleId));
  }

  const nextStatus = allocationCycleLifecycle.tryTransition(cycle.status, "reverse");
  if (!nextStatus) {
    return err(new InvalidStateError(input.allocationCycleId));
  }

  // Validate accounting period is OPEN or FUTURE_ENTERABLE
  const accountingPeriod = await db
    .selectFrom("AccountingPeriod")
    .where("id", "=", cycle.accountingPeriodId)
    .selectAll()
    .executeTakeFirst();

  const periodStatus = accountingPeriod?.status;
  if (periodStatus !== "OPEN" && periodStatus !== "FUTURE_ENTERABLE") {
    return err(new PeriodNotOpenError(input.allocationCycleId));
  }

  await createAllocationReversalEntries(db, cycle);

  const allocationCycle = await db
    .updateTable("AllocationCycle")
    .set({
      status: nextStatus,
      updatedAt: new Date(),
    })
    .where("id", "=", input.allocationCycleId)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ allocationCycle });
}
