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

const builtins = {
  productId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: product },
      backward: "productAttributeAssignments",
    })
    .description("Foreign key to Product"),
  attributeId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: productAttribute },
      backward: "productAttributeAssignments",
    })
    .description("Foreign key to ProductAttribute"),
  valueId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: productAttributeValue },
      backward: "productAttributeAssignments",
    })
    .description("Foreign key to ProductAttributeValue"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

export function createProductAttributeAssignmentType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateProductAttributeAssignmentTypeParams<F>) {
  return db
    .type("ProductAttributeAssignment", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["productId", "attributeId", "valueId"],
      unique: true,
      name: "product_attribute_assignment_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const productAttributeAssignment = createProductAttributeAssignmentType({});
