import type { DB } from "../generated/kysely-tailordb";
import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/module";

export interface GetAllocationCycleInput {
  id: string;
}

/**
 * Function: getAllocationCycle
 *
 * Retrieves a single allocation cycle by id, along with its rules and results.
 */
export async function run(db: ReadonlyDB<DB>, input: GetAllocationCycleInput) {
  const cycle = await db
    .selectFrom("AllocationCycle")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!cycle) {
    return ok({ allocationCycle: null, rules: [], results: [] });
  }

  const rules = await db
    .selectFrom("AllocationRule")
    .selectAll()
    .where("allocationCycleId", "=", input.id)
    .execute();

  const results = await db
    .selectFrom("AllocationResult")
    .selectAll()
    .where("allocationCycleId", "=", input.id)
    .execute();

  return ok({ allocationCycle: cycle, rules, results });
}
