import type { CollectionConfig } from 'payload'
import { monitoringAlertRulesAccess } from '../lib/access'

export const MonitoringAlertRules: CollectionConfig = {
  slug: 'monitoring-alert-rules',
  admin: {
    useAsTitle: 'name',
    group: 'Monitoring',
    description: 'Konfigurierbare Alert-Regeln',
    defaultColumns: ['name', 'metric', 'condition', 'threshold', 'severity', 'enabled'],
  },
  access: monitoringAlertRulesAccess,
  fields: [
    {
      name: 'name',
      type: 'text',
      required: true,
      label: 'Regelname',
    },
    {
      name: 'metric',
      type: 'text',
      required: true,
      label: 'Metrik-Pfad',
      admin: {
        description: 'z.B. system.cpuUsagePercent, services.redis.memoryUsedMB',
      },
    },
    {
      name: 'condition',
      type: 'select',
      required: true,
      options: [
        { label: 'Größer als (>)', value: 'gt' },
        { label: 'Kleiner als (<)', value: 'lt' },
        { label: 'Gleich (=)', value: 'eq' },
        { label: 'Größer gleich (>=)', value: 'gte' },
        { label: 'Kleiner gleich (<=)', value: 'lte' },
      ],
    },
    {
      name: 'threshold',
      type: 'number',
      required: true,
      label: 'Schwellenwert',
    },
    {
      name: 'severity',
      type: 'select',
      required: true,
      options: [
        { label: 'Warnung', value: 'warning' },
        { label: 'Fehler', value: 'error' },
        { label: 'Kritisch', value: 'critical' },
      ],
    },
    {
      name: 'channels',
      type: 'select',
      hasMany: true,
      required: true,
      options: [
        { label: 'E-Mail', value: 'email' },
        { label: 'Slack', value: 'slack' },
        { label: 'Discord', value: 'discord' },
      ],
      label: 'Benachrichtigungskanäle',
    },
    {
      name: 'recipients',
      type: 'group',
      label: 'Empfänger',
      fields: [
        {
          name: 'emails',
          type: 'array',
          label: 'E-Mail-Empfänger',
          fields: [
            { name: 'email', type: 'email', required: true },
          ],
        },
        {
          name: 'slackWebhook',
          type: 'text',
          label: 'Slack Webhook URL',
        },
        {
          name: 'discordWebhook',
          type: 'text',
          label: 'Discord Webhook URL',
        },
      ],
    },
    {
      name: 'cooldownMinutes',
      type: 'number',
      defaultValue: 15,
      min: 1,
      label: 'Cooldown (Minuten)',
      admin: {
        description: 'Minimaler Abstand zwischen gleichen Alerts',
      },
    },
    {
      name: 'enabled',
      type: 'checkbox',
      defaultValue: true,
      label: 'Aktiv',
    },
    {
      name: 'tenant',
      type: 'relationship',
      relationTo: 'tenants',
      label: 'Tenant',
      admin: {
        description: 'Optional: Tenant-spezifische Regel',
      },
    },
  ],
}
