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

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));
  }

  // Validate status is POSTED
  if (cycle.status !== "POSTED") {
    return err(new InvalidStateError(input.allocationCycleId));
  }

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

  const periodStatus = (accountingPeriod as Record<string, unknown>)?.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: "REVERSED",
      updatedAt: new Date(),
    })
    .where("id", "=", input.allocationCycleId)
    .returningAll()
    .executeTakeFirst();

  return ok({ allocationCycle: allocationCycle! });
}
