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

export interface InvalidateAllocationCycleInput {
  allocationCycleId: string;
}

export async function run(
  db: Transaction,
  input: InvalidateAllocationCycleInput,
  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 VALIDATED
  if (cycle.status !== "VALIDATED") {
    return err(new InvalidStateError(input.allocationCycleId));
  }

  // Transition to DRAFT
  const allocationCycle = await db
    .updateTable("AllocationCycle")
    .set({
      status: "DRAFT",
      updatedAt: new Date(),
    })
    .where("id", "=", input.allocationCycleId)
    .returningAll()
    .executeTakeFirst();

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