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

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

export function createAllocationResultType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateAllocationResultTypeParams<F>,
) {
  return db
    .type("AllocationResult", {
      allocationCycleId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.allocationCycleType ?? allocationCycle },
          backward: "results",
        })
        .description("Foreign key to AllocationCycle"),
      senderCostCenterId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.costCenterType ?? costCenter },
          backward: "allocationResultsAsSender",
        })
        .description("Foreign key to CostCenter (sender)"),
      receiverType: db.string().description("Polymorphic receiver type"),
      receiverId: db.uuid().description("Polymorphic receiver ID"),
      allocatedAmount: db.float().description("Allocated amount"),
      costElementId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.costElementType ?? costElement },
          backward: "allocationResults",
        })
        .description("Foreign key to CostElement"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const allocationResult = createAllocationResultType({});
