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

const builtins = {
  attributeId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: productAttribute },
      backward: "productAttributeValues",
    })
    .description("Foreign key to ProductAttribute"),
  label: db.string().description("Display label for this value option"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

export function createProductAttributeValueType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateProductAttributeValueTypeParams<F>,
) {
  return db
    .type("ProductAttributeValue", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["attributeId", "label"],
      unique: true,
      name: "product_attribute_value_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const productAttributeValue = createProductAttributeValueType({});
