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

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

export function createProductCategoryAssignmentType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateProductCategoryAssignmentTypeParams<F>) {
  return db
    .type("ProductCategoryAssignment", {
      productId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: product },
          backward: "productCategoryAssignments",
        })
        .description("Foreign key to Product"),
      categoryId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: productCategory },
          backward: "productCategoryAssignments",
        })
        .description("Foreign key to ProductCategory"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["productId", "categoryId"],
      unique: true,
      name: "product_category_assignment_unique_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const productCategoryAssignment = createProductCategoryAssignmentType({});
