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

const builtins = {
  eventType: db.string().description("Event type key matching an EventCategoryBinding row"),
  channelId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: notificationChannel },
      backward: "notificationTemplates",
    })
    .description("Foreign key to NotificationChannel this template renders for"),
  locale: db
    .string()
    .description("Locale tag (e.g., en-US, ja-JP) for which this template applies"),
  subject: db.string().description("Rendered subject line; may include {{variable}} tokens"),
  body: db.string().description("Plain-text body with {{variable}} substitution support"),
  htmlBody: db
    .string({ optional: true })
    .description("Optional HTML body for channels that support rich content"),
  variableSchema: db
    .string()
    .description(
      "JSON-encoded schema describing required and optional render variables (name, type, required)",
    ),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

export function createNotificationTemplateType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateNotificationTemplateTypeParams<F>,
) {
  return db
    .type("NotificationTemplate", {
      ...builtins,
      ...params.fields,
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["eventType", "channelId", "locale"],
      unique: true,
      name: "notification_template_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const notificationTemplate = createNotificationTemplateType({});
