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 { productCategory } from "./productCategory";

const builtins = {
  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"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

export function createProductCategoryAssignmentType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateProductCategoryAssignmentTypeParams<F>) {
  return db
    .type("ProductCategoryAssignment", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["productId", "categoryId"],
      unique: true,
      name: "product_category_assignment_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const productCategoryAssignment = createProductCategoryAssignmentType({});
