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 category code"),
  name: db.string().description("Category display name"),
  parentId: db
    .uuid({ optional: true })
    .relation({
      type: "n-1",
      toward: { type: "self" },
      backward: "children",
    })
    .description("Parent category ID (null for root categories)"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

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

export const productCategory = createProductCategoryType({});
