import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField } from "@tailor-platform/sdk";

const builtins = {
  code: db.string().unique().description("Globally unique, immutable node code"),
  name: db.string().description("Display name for the taxonomy node"),
  parentId: db
    .uuid({ optional: true })
    .relation({
      type: "n-1",
      toward: { type: "self" },
      backward: "children",
    })
    .description("Parent node ID (null for root nodes)"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

export interface CreateTaxonomyNodeTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: NoReservedFields<F, ReservedFields>;
}

export function createTaxonomyNodeType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateTaxonomyNodeTypeParams<F>,
) {
  return db
    .type("TaxonomyNode", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const taxonomyNode = createTaxonomyNodeType({});
