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

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

export function createItemTaxonomyAssignmentType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateItemTaxonomyAssignmentTypeParams<F>,
) {
  return db
    .type("ItemTaxonomyAssignment", {
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: item },
          backward: "itemTaxonomyAssignments",
        })
        .description("Foreign key to Item"),
      taxonomyNodeId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: taxonomyNode },
          backward: "itemTaxonomyAssignments",
        })
        .description("Foreign key to TaxonomyNode"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["itemId", "taxonomyNodeId"],
      unique: true,
      name: "item_taxonomy_assignment_unique_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const itemTaxonomyAssignment = createItemTaxonomyAssignmentType({});
