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

export const NOTIFICATION_CHANNEL_IDS = [
  "IN_APP",
  "EMAIL",
  "SMS",
  "PUSH",
  "SLACK",
  "TEAMS",
] as const;

export const NOTIFICATION_CHANNEL_KINDS = ["PERSONAL", "DESTINATION"] as const;

const builtins = {
  channelId: db
    .enum(NOTIFICATION_CHANNEL_IDS)
    .unique()
    .description("Reserved channel identifier (IN_APP, EMAIL, SMS, PUSH, SLACK, TEAMS)"),
  kind: db
    .enum(NOTIFICATION_CHANNEL_KINDS)
    .description(
      "Delivery topology: PERSONAL (per-recipient fan-out) or DESTINATION (one post per ChannelRoutingBinding)",
    ),
  displayName: db.string().description("Admin-facing display label for the channel"),
  capabilities: db
    .object({
      supportsHtmlBody: db.bool(),
      supportsAttachments: db.bool(),
      supportsRichActions: db.bool(),
    })
    .description("Intrinsic medium capabilities used by template rendering for branching"),
  enabled: db
    .bool()
    .description("Kill-switch; when false the dispatcher skips this channel for every event"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

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

export const notificationChannel = createNotificationChannelType({});
