// src/collections/ReportSchedules.ts
// Scheduled Community Reports Collection

import type { CollectionConfig } from 'payload'
import { hasYouTubeAccess, isYouTubeManager } from '../lib/youtubeAccess'

/**
 * ReportSchedules Collection
 *
 * Ermöglicht die Planung automatischer Community-Reports.
 * Reports werden per E-Mail an definierte Empfänger gesendet.
 * Teil des Community Management Dashboards.
 */
export const ReportSchedules: CollectionConfig = {
  slug: 'report-schedules',
  labels: {
    singular: 'Report-Zeitplan',
    plural: 'Report-Zeitpläne',
  },
  admin: {
    group: 'Community',
    useAsTitle: 'name',
    defaultColumns: ['name', 'reportType', 'frequency', 'enabled', 'lastSentAt'],
    description: 'Automatische Community-Reports per E-Mail',
  },
  access: {
    read: hasYouTubeAccess,
    create: isYouTubeManager,
    update: isYouTubeManager,
    delete: isYouTubeManager,
  },
  fields: [
    // === Grundeinstellungen ===
    {
      name: 'name',
      type: 'text',
      required: true,
      label: 'Report-Name',
      admin: {
        description: 'Interner Name für diesen Report-Zeitplan',
      },
    },
    {
      name: 'enabled',
      type: 'checkbox',
      defaultValue: true,
      label: 'Aktiv',
      admin: {
        description: 'Deaktivierte Reports werden nicht automatisch versendet',
      },
    },

    // === Zeitplan ===
    {
      type: 'row',
      fields: [
        {
          name: 'frequency',
          type: 'select',
          required: true,
          label: 'Häufigkeit',
          defaultValue: 'weekly',
          options: [
            { label: 'Täglich', value: 'daily' },
            { label: 'Wöchentlich', value: 'weekly' },
            { label: 'Monatlich', value: 'monthly' },
          ],
          admin: {
            width: '33%',
          },
        },
        {
          name: 'dayOfWeek',
          type: 'select',
          label: 'Wochentag',
          options: [
            { label: 'Montag', value: 'monday' },
            { label: 'Dienstag', value: 'tuesday' },
            { label: 'Mittwoch', value: 'wednesday' },
            { label: 'Donnerstag', value: 'thursday' },
            { label: 'Freitag', value: 'friday' },
            { label: 'Samstag', value: 'saturday' },
            { label: 'Sonntag', value: 'sunday' },
          ],
          admin: {
            width: '33%',
            condition: (data) => data?.frequency === 'weekly',
            description: 'Für wöchentliche Reports',
          },
        },
        {
          name: 'dayOfMonth',
          type: 'number',
          label: 'Tag des Monats',
          min: 1,
          max: 28,
          admin: {
            width: '33%',
            condition: (data) => data?.frequency === 'monthly',
            description: 'Für monatliche Reports (1-28)',
          },
        },
      ],
    },
    {
      type: 'row',
      fields: [
        {
          name: 'time',
          type: 'text',
          required: true,
          defaultValue: '08:00',
          label: 'Uhrzeit',
          admin: {
            width: '50%',
            description: 'Format: HH:MM (24-Stunden)',
          },
          validate: (value: string | null | undefined) => {
            if (!value) return true
            const regex = /^([01]\d|2[0-3]):([0-5]\d)$/
            if (!regex.test(value)) {
              return 'Bitte gültiges Format verwenden: HH:MM (z.B. 08:00)'
            }
            return true
          },
        },
        {
          name: 'timezone',
          type: 'select',
          required: true,
          defaultValue: 'Europe/Berlin',
          label: 'Zeitzone',
          options: [
            { label: 'Europe/Berlin (MEZ/MESZ)', value: 'Europe/Berlin' },
            { label: 'Europe/London (GMT/BST)', value: 'Europe/London' },
            { label: 'America/New_York (EST/EDT)', value: 'America/New_York' },
            { label: 'America/Los_Angeles (PST/PDT)', value: 'America/Los_Angeles' },
            { label: 'Asia/Tokyo (JST)', value: 'Asia/Tokyo' },
            { label: 'UTC', value: 'UTC' },
          ],
          admin: {
            width: '50%',
          },
        },
      ],
    },

    // === Report-Inhalt ===
    {
      name: 'reportType',
      type: 'select',
      required: true,
      label: 'Report-Typ',
      defaultValue: 'overview',
      options: [
        { label: 'Übersicht', value: 'overview' },
        { label: 'Sentiment-Analyse', value: 'sentiment_analysis' },
        { label: 'Antwort-Metriken', value: 'response_metrics' },
        { label: 'Content-Performance', value: 'content_performance' },
        { label: 'Vollständiger Report', value: 'full_report' },
      ],
      admin: {
        description: 'Art der Daten im Report',
      },
    },
    {
      name: 'channels',
      type: 'relationship',
      relationTo: 'social-accounts',
      hasMany: true,
      label: 'Kanäle',
      admin: {
        description: 'Leer = alle aktiven Kanäle. Oder spezifische Kanäle auswählen.',
      },
    },
    {
      name: 'periodDays',
      type: 'number',
      defaultValue: 7,
      label: 'Zeitraum (Tage)',
      min: 1,
      max: 90,
      admin: {
        description: 'Wie viele Tage zurück sollen analysiert werden?',
      },
    },

    // === Format & Versand ===
    {
      name: 'format',
      type: 'select',
      required: true,
      defaultValue: 'pdf',
      label: 'Format',
      options: [
        { label: 'PDF', value: 'pdf' },
        { label: 'Excel', value: 'excel' },
        { label: 'HTML E-Mail', value: 'html_email' },
      ],
    },
    {
      name: 'recipients',
      type: 'array',
      required: true,
      minRows: 1,
      label: 'Empfänger',
      fields: [
        {
          type: 'row',
          fields: [
            {
              name: 'email',
              type: 'email',
              required: true,
              label: 'E-Mail',
              admin: {
                width: '60%',
              },
            },
            {
              name: 'name',
              type: 'text',
              label: 'Name',
              admin: {
                width: '40%',
                description: 'Optional',
              },
            },
          ],
        },
      ],
    },

    // === Status (Read-only) ===
    {
      type: 'collapsible',
      label: 'Status & Statistiken',
      admin: {
        initCollapsed: true,
      },
      fields: [
        {
          type: 'row',
          fields: [
            {
              name: 'lastSentAt',
              type: 'date',
              label: 'Zuletzt gesendet',
              admin: {
                width: '50%',
                readOnly: true,
                date: {
                  pickerAppearance: 'dayAndTime',
                  displayFormat: 'dd.MM.yyyy HH:mm',
                },
              },
            },
            {
              name: 'nextScheduledAt',
              type: 'date',
              label: 'Nächster Versand',
              admin: {
                width: '50%',
                readOnly: true,
                date: {
                  pickerAppearance: 'dayAndTime',
                  displayFormat: 'dd.MM.yyyy HH:mm',
                },
              },
            },
          ],
        },
        {
          type: 'row',
          fields: [
            {
              name: 'sendCount',
              type: 'number',
              defaultValue: 0,
              label: 'Anzahl Versendungen',
              admin: {
                width: '50%',
                readOnly: true,
              },
            },
            {
              name: 'lastError',
              type: 'text',
              label: 'Letzter Fehler',
              admin: {
                width: '50%',
                readOnly: true,
              },
            },
          ],
        },
      ],
    },
  ],
  timestamps: true,
  hooks: {
    beforeChange: [
      // Berechne nächsten geplanten Versand
      async ({ data, operation }) => {
        if (!data) return data

        if (operation === 'create' || data.enabled) {
          data.nextScheduledAt = calculateNextScheduledTime(data)
        }

        return data
      },
    ],
  },
}

/**
 * Berechnet den nächsten geplanten Versandzeitpunkt
 */
function calculateNextScheduledTime(data: {
  frequency?: string
  dayOfWeek?: string
  dayOfMonth?: number
  time?: string
  timezone?: string
}): Date | null {
  if (!data.frequency || !data.time) return null

  const [hours, minutes] = data.time.split(':').map(Number)
  const now = new Date()

  // Einfache Berechnung (ohne Timezone-Bibliothek)
  // In Production sollte luxon oder date-fns-tz verwendet werden
  const next = new Date()
  next.setHours(hours, minutes, 0, 0)

  // Wenn die Zeit heute schon vorbei ist, auf morgen setzen
  if (next <= now) {
    next.setDate(next.getDate() + 1)
  }

  switch (data.frequency) {
    case 'daily':
      // Bereits korrekt
      break

    case 'weekly':
      const dayMap: Record<string, number> = {
        sunday: 0,
        monday: 1,
        tuesday: 2,
        wednesday: 3,
        thursday: 4,
        friday: 5,
        saturday: 6,
      }
      const targetDay = dayMap[data.dayOfWeek || 'monday']
      const currentDay = next.getDay()
      let daysUntil = targetDay - currentDay
      if (daysUntil <= 0) daysUntil += 7
      next.setDate(next.getDate() + daysUntil - 1) // -1 weil wir schon +1 gemacht haben
      break

    case 'monthly':
      const targetDate = data.dayOfMonth || 1
      next.setDate(targetDate)
      if (next <= now) {
        next.setMonth(next.getMonth() + 1)
      }
      break
  }

  return next
}

export default ReportSchedules
