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

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

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

export function createItemTaxonomyAssignmentType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateItemTaxonomyAssignmentTypeParams<F>,
) {
  return db
    .type("ItemTaxonomyAssignment", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["itemId", "taxonomyNodeId"],
      unique: true,
      name: "item_taxonomy_assignment_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const itemTaxonomyAssignment = createItemTaxonomyAssignmentType({});
