import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { company as companyStub } from "../lib/_db_deps";

export interface CreateProfitCenterHierarchyTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  companyType?: TailorAnyDBType;
}

export function createProfitCenterHierarchyType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateProfitCenterHierarchyTypeParams<F>,
) {
  return db
    .type("ProfitCenterHierarchy", {
      name: db.string().description("Hierarchy name"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "profitCenterHierarchies",
        })
        .description("Foreign key to Company"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const profitCenterHierarchy = createProfitCenterHierarchyType({});
