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

const builtins = {
  eventType: db
    .string()
    .unique()
    .description("Emitter-supplied event type identifier; primary key of the seeded catalog"),
  categoryId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: notificationCategory },
      backward: "eventCategoryBindings",
    })
    .description("Foreign key to NotificationCategory bucket"),
  transactional: db
    .bool()
    .description("When true, dispatcher bypasses the preference filter for events of this type"),
  defaultChannels: db
    .string({ array: true })
    .description("Default channelIds the dispatcher fans out to when no preference applies"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

export function createEventCategoryBindingType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateEventCategoryBindingTypeParams<F>,
) {
  return db
    .type("EventCategoryBinding", {
      ...builtins,
      ...params.fields,
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const eventCategoryBinding = createEventCategoryBindingType({});
