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 ExecuteAllocationCycleInput {
  allocationCycleId: string;
  costElementId: string;
  mode: "ACTUAL" | "TEST_RUN";
}

export async function run(
  db: Transaction,
  input: ExecuteAllocationCycleInput,
  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));
  }

  // Fetch all rules for this cycle
  const rules = await db
    .selectFrom("AllocationRule")
    .selectAll()
    .where("allocationCycleId", "=", input.allocationCycleId)
    .execute();

  const typedRules = rules as {
    senderCostCenterId: string;
    receiverType: string;
    receiverId: string;
    percentage: number;
  }[];

  if (input.mode === "TEST_RUN") {
    // Return preview results without status change
    const previewResults = typedRules.map((rule) => ({
      allocationCycleId: input.allocationCycleId,
      senderCostCenterId: rule.senderCostCenterId,
      receiverType: rule.receiverType,
      receiverId: rule.receiverId,
      allocatedAmount: 0,
      costElementId: input.costElementId,
    }));
    return ok({ allocationCycle: cycle, allocationResults: previewResults });
  }

  // ACTUAL mode: create AllocationResult records
  const allocationResults = [];
  for (const rule of typedRules) {
    const result = await db
      .insertInto("AllocationResult")
      .values({
        allocationCycleId: input.allocationCycleId,
        senderCostCenterId: rule.senderCostCenterId,
        receiverType: rule.receiverType,
        receiverId: rule.receiverId,
        allocatedAmount: 0,
        costElementId: input.costElementId,
        createdAt: new Date(),
        updatedAt: null,
      })
      .returningAll()
      .executeTakeFirst();
    allocationResults.push(result!);
  }

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

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