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

export interface CreateProfitCenterHierarchyAssignmentTypeParams<
  F extends Record<string, TailorAnyDBField>,
> {
  fields?: F;
  profitCenterType?: TailorAnyDBType;
  profitCenterHierarchyType?: TailorAnyDBType;
  profitCenterHierarchyNodeType?: TailorAnyDBType;
}

export function createProfitCenterHierarchyAssignmentType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateProfitCenterHierarchyAssignmentTypeParams<F>) {
  return db
    .type("ProfitCenterHierarchyAssignment", {
      profitCenterId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.profitCenterType ?? profitCenter },
          backward: "hierarchyAssignments",
        })
        .description("Foreign key to ProfitCenter"),
      hierarchyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.profitCenterHierarchyType ?? profitCenterHierarchy },
          backward: "profitCenterAssignments",
        })
        .description("Foreign key to ProfitCenterHierarchy"),
      hierarchyNodeId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.profitCenterHierarchyNodeType ?? profitCenterHierarchyNode },
          backward: "profitCenterAssignments",
        })
        .description("Foreign key to ProfitCenterHierarchyNode"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["profitCenterId", "hierarchyId"],
      unique: true,
      name: "profit_center_hierarchy_assignment_unique_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const profitCenterHierarchyAssignment = createProfitCenterHierarchyAssignmentType({});
