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 DeleteAllocationCycleInput {
  allocationCycleId: string;
}

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

  // Delete associated rules first
  await db
    .deleteFrom("AllocationRule")
    .where("allocationCycleId", "=", input.allocationCycleId)
    .execute();

  // Delete the cycle
  await db.deleteFrom("AllocationCycle").where("id", "=", input.allocationCycleId).execute();

  return ok({ allocationCycleId: input.allocationCycleId });
}
