import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { allocationCycle } from "./allocationCycle";
import { costCenter } from "./costCenter";

export interface CreateAllocationRuleTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  allocationCycleType?: TailorAnyDBType;
  costCenterType?: TailorAnyDBType;
}

export function createAllocationRuleType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateAllocationRuleTypeParams<F>,
) {
  return db
    .type("AllocationRule", {
      allocationCycleId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.allocationCycleType ?? allocationCycle },
          backward: "rules",
        })
        .description("Foreign key to AllocationCycle"),
      senderCostCenterId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.costCenterType ?? costCenter },
          backward: "allocationRulesAsSender",
        })
        .description("Foreign key to CostCenter (sender)"),
      receiverType: db.string().description("Polymorphic receiver type"),
      receiverId: db.uuid().description("Polymorphic receiver ID"),
      percentage: db.float().description("Allocation percentage"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const allocationRule = createAllocationRuleType({});
