import {
  db,
  type TailorAnyDBField,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { product } from "./product";
import { productAttribute } from "./productAttribute";
import { productAttributeValue } from "./productAttributeValue";

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

export function createProductAttributeAssignmentType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateProductAttributeAssignmentTypeParams<F>) {
  return db
    .type("ProductAttributeAssignment", {
      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"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["productId", "attributeId", "valueId"],
      unique: true,
      name: "product_attribute_assignment_unique_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const productAttributeAssignment = createProductAttributeAssignmentType({});
