// src/lib/services/ReportGeneratorService.ts
// Automatische Community Report Generierung

import { Payload } from 'payload'
import { generatePdfFromHtml } from '../pdf/pdf-service'
import { sendTenantEmail } from '../email/tenant-email-service'

// =============================================================================
// Types
// =============================================================================

export type ReportType =
  | 'overview'
  | 'sentiment_analysis'
  | 'response_metrics'
  | 'content_performance'
  | 'full_report'

export type ReportFormat = 'pdf' | 'excel' | 'html_email'

export interface ReportSchedule {
  id: number
  name: string
  enabled: boolean
  frequency: 'daily' | 'weekly' | 'monthly'
  dayOfWeek?: string
  dayOfMonth?: number
  time: string
  timezone: string
  reportType: ReportType
  channels?: { id: number; displayName?: string }[]
  periodDays: number
  format: ReportFormat
  recipients: { email: string; name?: string }[]
}

export interface ReportData {
  schedule: ReportSchedule
  generatedAt: Date
  periodStart: Date
  periodEnd: Date
  overview?: OverviewData
  sentimentAnalysis?: SentimentData
  responseMetrics?: ResponseData
  contentPerformance?: ContentData
}

export interface OverviewData {
  totalInteractions: number
  newInteractions: number
  repliedCount: number
  avgResponseTime: number
  platforms: { platform: string; count: number }[]
}

export interface SentimentData {
  positive: number
  neutral: number
  negative: number
  trend: { date: string; positive: number; neutral: number; negative: number }[]
}

export interface ResponseData {
  avgResponseTimeHours: number
  responseRate: number
  repliedCount: number
  pendingCount: number
  byPlatform: { platform: string; avgTime: number; rate: number }[]
}

export interface ContentData {
  topPosts: {
    title: string
    platform: string
    comments: number
    engagement: number
  }[]
  topTopics: { topic: string; count: number }[]
}

export interface ReportResult {
  success: boolean
  format: ReportFormat
  buffer?: Buffer
  html?: string
  filename?: string
  mimeType?: string
  error?: string
}

// =============================================================================
// Report Generator Service
// =============================================================================

export class ReportGeneratorService {
  private payload: Payload

  constructor(payload: Payload) {
    this.payload = payload
  }

  /**
   * Generiert einen Report basierend auf dem Schedule
   */
  async generateReport(schedule: ReportSchedule): Promise<ReportResult> {
    try {
      // Daten sammeln
      const data = await this.collectReportData(schedule)

      // Report im gewünschten Format generieren
      switch (schedule.format) {
        case 'pdf':
          return this.generatePdfReport(data)
        case 'excel':
          return this.generateExcelReport(data)
        case 'html_email':
          return this.generateHtmlEmail(data)
        default:
          throw new Error(`Unsupported format: ${schedule.format}`)
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error)
      console.error('[ReportGenerator] Error generating report:', error)
      return {
        success: false,
        format: schedule.format,
        error: message,
      }
    }
  }

  /**
   * Ermittelt die Tenant-ID aus den Channels des Schedules.
   * Fällt auf Tenant 1 (porwoll.de) zurück wenn kein Channel vorhanden.
   */
  private async resolveTenantId(schedule: ReportSchedule): Promise<number> {
    if (schedule.channels && schedule.channels.length > 0) {
      const firstChannel = schedule.channels[0]
      const channelId = typeof firstChannel === 'object' ? firstChannel.id : firstChannel
      try {
        const account = await this.payload.findByID({
          collection: 'social-accounts',
          id: channelId,
          depth: 0,
          overrideAccess: true,
        })
        const tenant = (account as unknown as Record<string, unknown>)?.tenant
        if (typeof tenant === 'number') return tenant
        if (typeof tenant === 'object' && tenant && 'id' in (tenant as Record<string, unknown>)) {
          return (tenant as { id: number }).id
        }
      } catch {
        // Channel nicht gefunden, Fallback verwenden
      }
    }
    return 1 // Default: porwoll.de
  }

  /**
   * Sendet einen generierten Report per E-Mail
   */
  async sendReport(schedule: ReportSchedule, report: ReportResult): Promise<boolean> {
    if (!report.success) {
      console.error('[ReportGenerator] Cannot send failed report')
      return false
    }

    const subject = `Community Report: ${schedule.name} - ${new Date().toLocaleDateString('de-DE')}`
    const recipients = schedule.recipients.map((r) => r.email)
    const tenantId = await this.resolveTenantId(schedule)

    try {
      for (const email of recipients) {
        if (schedule.format === 'html_email' && report.html) {
          // HTML direkt als E-Mail-Body
          await sendTenantEmail(this.payload, tenantId, {
            to: email,
            subject,
            html: report.html,
            source: 'system',
          })
        } else if (report.buffer && report.filename && report.mimeType) {
          // PDF oder Excel als Attachment
          await sendTenantEmail(this.payload, tenantId, {
            to: email,
            subject,
            html: this.generateEmailBody(schedule),
            attachments: [
              {
                filename: report.filename,
                content: report.buffer,
                contentType: report.mimeType,
              },
            ],
            source: 'system',
          })
        }
      }

      // Update schedule stats
      const existingSendCount = (await this.getSchedule(schedule.id))?.sendCount ?? 0
      await this.payload.update({
        collection: 'report-schedules',
        id: schedule.id,
        data: {
          lastSentAt: new Date().toISOString(),
          sendCount: existingSendCount + 1,
          lastError: null,
        },
      })

      return true
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error)
      console.error('[ReportGenerator] Error sending report:', error)

      await this.payload.update({
        collection: 'report-schedules',
        id: schedule.id,
        data: {
          lastError: message,
        },
      })

      return false
    }
  }

  /**
   * Sammelt Daten für den Report
   */
  private async collectReportData(schedule: ReportSchedule): Promise<ReportData> {
    const periodEnd = new Date()
    const periodStart = new Date()
    periodStart.setDate(periodStart.getDate() - schedule.periodDays)

    const channelIds = schedule.channels?.map((c) => c.id)

    const data: ReportData = {
      schedule,
      generatedAt: new Date(),
      periodStart,
      periodEnd,
    }

    // Daten je nach Report-Typ sammeln
    const types =
      schedule.reportType === 'full_report'
        ? ['overview', 'sentiment_analysis', 'response_metrics', 'content_performance']
        : [schedule.reportType]

    for (const type of types) {
      switch (type) {
        case 'overview':
          data.overview = await this.collectOverviewData(periodStart, channelIds)
          break
        case 'sentiment_analysis':
          data.sentimentAnalysis = await this.collectSentimentData(periodStart, channelIds)
          break
        case 'response_metrics':
          data.responseMetrics = await this.collectResponseData(periodStart, channelIds)
          break
        case 'content_performance':
          data.contentPerformance = await this.collectContentData(periodStart, channelIds)
          break
      }
    }

    return data
  }

  /**
   * Sammelt Übersichtsdaten
   */
  private async collectOverviewData(
    since: Date,
    channelIds?: number[]
  ): Promise<OverviewData> {
    const where: any = {
      createdAt: { greater_than: since.toISOString() },
    }

    if (channelIds && channelIds.length > 0) {
      where.socialAccount = { in: channelIds }
    }

    const interactions = await this.payload.find({
      collection: 'community-interactions',
      where,
      limit: 1000,
    })

    const docs = interactions.docs as any[]

    const replied = docs.filter((i) => i.status === 'replied')
    const platforms = docs.reduce(
      (acc, i) => {
        const platform = this.resolvePlatformName(i.platform)
        acc[platform] = (acc[platform] || 0) + 1
        return acc
      },
      {} as Record<string, number>
    )

    // Durchschnittliche Antwortzeit berechnen
    let totalResponseTime = 0
    let responseCount = 0
    for (const interaction of replied) {
      if (interaction.response?.sentAt && interaction.createdAt) {
        const responseTime =
          new Date(interaction.response.sentAt as string).getTime() -
          new Date(interaction.createdAt as string).getTime()
        totalResponseTime += responseTime
        responseCount++
      }
    }

    return {
      totalInteractions: interactions.totalDocs,
      newInteractions: docs.filter((i) => i.status === 'new').length,
      repliedCount: replied.length,
      avgResponseTime: responseCount > 0 ? totalResponseTime / responseCount / (1000 * 60 * 60) : 0,
      platforms: Object.entries(platforms).map(([platform, count]) => ({
        platform,
        count: typeof count === 'number' ? count : 0,
      })),
    }
  }

  /**
   * Sammelt Sentiment-Daten
   */
  private async collectSentimentData(
    since: Date,
    channelIds?: number[]
  ): Promise<SentimentData> {
    const where: any = {
      createdAt: { greater_than: since.toISOString() },
    }

    if (channelIds && channelIds.length > 0) {
      where.socialAccount = { in: channelIds }
    }

    const interactions = await this.payload.find({
      collection: 'community-interactions',
      where,
      limit: 1000,
    })

    const docs = interactions.docs as any[]

    let positive = 0
    let neutral = 0
    let negative = 0

    const dailyData: Record<string, { positive: number; neutral: number; negative: number }> = {}

    for (const interaction of docs) {
      const sentiment = interaction.analysis?.sentiment || 'neutral'
      const date = new Date(interaction.createdAt as string).toISOString().split('T')[0]

      if (!dailyData[date]) {
        dailyData[date] = { positive: 0, neutral: 0, negative: 0 }
      }

      if (sentiment === 'positive') {
        positive++
        dailyData[date].positive++
      } else if (sentiment === 'negative') {
        negative++
        dailyData[date].negative++
      } else {
        neutral++
        dailyData[date].neutral++
      }
    }

    return {
      positive,
      neutral,
      negative,
      trend: Object.entries(dailyData)
        .sort(([a], [b]) => a.localeCompare(b))
        .map(([date, data]) => ({ date, ...data })),
    }
  }

  /**
   * Sammelt Response-Metriken
   */
  private async collectResponseData(
    since: Date,
    channelIds?: number[]
  ): Promise<ResponseData> {
    const where: any = {
      createdAt: { greater_than: since.toISOString() },
    }

    if (channelIds && channelIds.length > 0) {
      where.socialAccount = { in: channelIds }
    }

    const interactions = await this.payload.find({
      collection: 'community-interactions',
      where,
      limit: 1000,
    })

    const docs = interactions.docs as any[]

    const replied = docs.filter((i) => i.status === 'replied')
    const pending = docs.filter((i) => i.status === 'new' || i.status === 'in_review')

    // Berechne durchschnittliche Antwortzeit
    let totalTime = 0
    let count = 0
    const platformData: Record<string, { totalTime: number; count: number; replied: number }> = {}

    for (const interaction of docs) {
      const platform = this.resolvePlatformName(interaction.platform)
      if (!platformData[platform]) {
        platformData[platform] = { totalTime: 0, count: 0, replied: 0 }
      }
      platformData[platform].count++

      if (interaction.status === 'replied' && interaction.response?.sentAt && interaction.createdAt) {
        const responseTime =
          new Date(interaction.response.sentAt as string).getTime() -
          new Date(interaction.createdAt as string).getTime()
        totalTime += responseTime
        count++
        platformData[platform].totalTime += responseTime
        platformData[platform].replied++
      }
    }

    return {
      avgResponseTimeHours: count > 0 ? totalTime / count / (1000 * 60 * 60) : 0,
      responseRate: interactions.totalDocs > 0 ? (replied.length / interactions.totalDocs) * 100 : 0,
      repliedCount: replied.length,
      pendingCount: pending.length,
      byPlatform: Object.entries(platformData).map(([platform, data]) => ({
        platform,
        avgTime: data.replied > 0 ? data.totalTime / data.replied / (1000 * 60 * 60) : 0,
        rate: data.count > 0 ? (data.replied / data.count) * 100 : 0,
      })),
    }
  }

  /**
   * Sammelt Content-Performance-Daten
   */
  private async collectContentData(
    since: Date,
    channelIds?: number[]
  ): Promise<ContentData> {
    const where: any = {
      createdAt: { greater_than: since.toISOString() },
    }

    if (channelIds && channelIds.length > 0) {
      where.socialAccount = { in: channelIds }
    }

    const interactions = await this.payload.find({
      collection: 'community-interactions',
      where,
      limit: 1000,
    })

    const docs = interactions.docs as any[]

    // Top Posts nach Kommentaren gruppieren
    const postData: Record<string, { title: string; platform: string; comments: number }> = {}
    const topicCount: Record<string, number> = {}

    for (const interaction of docs) {
      const linkedContent = interaction.linkedContent
      const postId =
        typeof linkedContent === 'object' && linkedContent && 'id' in linkedContent
          ? String((linkedContent as { id: number }).id)
          : typeof linkedContent === 'number'
            ? String(linkedContent)
            : 'unknown'
      const platform = this.resolvePlatformName(interaction.platform)
      const title = this.resolveContentTitle(linkedContent, postId)

      if (!postData[postId]) {
        postData[postId] = { title, platform, comments: 0 }
      }
      postData[postId].comments++

      // Topics aus AI-Analyse sammeln
      const topics = Array.isArray(interaction.analysis?.topics)
        ? interaction.analysis.topics
        : []
      for (const topic of topics) {
        const topicName =
          typeof topic === 'string'
            ? topic
            : (topic as { topic?: string | null })?.topic || ''
        if (!topicName) continue
        topicCount[topicName] = (topicCount[topicName] || 0) + 1
      }
    }

    return {
      topPosts: Object.values(postData)
        .sort((a, b) => b.comments - a.comments)
        .slice(0, 10)
        .map((p) => ({ ...p, engagement: p.comments })),
      topTopics: Object.entries(topicCount)
        .sort(([, a], [, b]) => b - a)
        .slice(0, 15)
        .map(([topic, count]) => ({ topic, count })),
    }
  }

  /**
   * Generiert PDF-Report
   */
  private async generatePdfReport(data: ReportData): Promise<ReportResult> {
    const html = this.generateReportHtml(data, true)
    const filename = `report-${data.schedule.name.toLowerCase().replace(/\s+/g, '-')}-${
      new Date().toISOString().split('T')[0]
    }.pdf`

    try {
      const result = await generatePdfFromHtml(html)

      if (!result.success || !result.buffer) {
        throw new Error(result.error || 'PDF generation failed')
      }

      return {
        success: true,
        format: 'pdf',
        buffer: result.buffer,
        filename,
        mimeType: 'application/pdf',
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error)
      return {
        success: false,
        format: 'pdf',
        error: message,
      }
    }
  }

  /**
   * Generiert Excel-Report
   */
  private async generateExcelReport(data: ReportData): Promise<ReportResult> {
    // Einfache CSV-Generierung als Fallback (xlsx würde extra Dependency benötigen)
    const filename = `report-${data.schedule.name.toLowerCase().replace(/\s+/g, '-')}-${
      new Date().toISOString().split('T')[0]
    }.csv`

    const rows: string[] = []
    rows.push(`Community Report: ${data.schedule.name}`)
    rows.push(`Zeitraum: ${data.periodStart.toLocaleDateString('de-DE')} - ${data.periodEnd.toLocaleDateString('de-DE')}`)
    rows.push('')

    if (data.overview) {
      rows.push('=== ÜBERSICHT ===')
      rows.push(`Gesamt Interaktionen,${data.overview.totalInteractions}`)
      rows.push(`Neue Interaktionen,${data.overview.newInteractions}`)
      rows.push(`Beantwortet,${data.overview.repliedCount}`)
      rows.push(`Durchschn. Antwortzeit (Std),${data.overview.avgResponseTime.toFixed(1)}`)
      rows.push('')
      rows.push('Plattform,Anzahl')
      for (const p of data.overview.platforms) {
        rows.push(`${p.platform},${p.count}`)
      }
      rows.push('')
    }

    if (data.sentimentAnalysis) {
      rows.push('=== SENTIMENT-ANALYSE ===')
      rows.push(`Positiv,${data.sentimentAnalysis.positive}`)
      rows.push(`Neutral,${data.sentimentAnalysis.neutral}`)
      rows.push(`Negativ,${data.sentimentAnalysis.negative}`)
      rows.push('')
    }

    if (data.responseMetrics) {
      rows.push('=== ANTWORT-METRIKEN ===')
      rows.push(`Durchschn. Antwortzeit (Std),${data.responseMetrics.avgResponseTimeHours.toFixed(1)}`)
      rows.push(`Antwortrate (%),${data.responseMetrics.responseRate.toFixed(1)}`)
      rows.push(`Beantwortet,${data.responseMetrics.repliedCount}`)
      rows.push(`Ausstehend,${data.responseMetrics.pendingCount}`)
      rows.push('')
    }

    if (data.contentPerformance) {
      rows.push('=== TOP CONTENT ===')
      rows.push('Titel,Plattform,Kommentare')
      for (const post of data.contentPerformance.topPosts) {
        rows.push(`"${post.title}",${post.platform},${post.comments}`)
      }
      rows.push('')
      rows.push('=== TOP THEMEN ===')
      rows.push('Thema,Anzahl')
      for (const topic of data.contentPerformance.topTopics) {
        rows.push(`${topic.topic},${topic.count}`)
      }
    }

    const buffer = Buffer.from(rows.join('\n'), 'utf-8')

    return {
      success: true,
      format: 'excel',
      buffer,
      filename,
      mimeType: 'text/csv',
    }
  }

  /**
   * Generiert HTML-Email
   */
  private async generateHtmlEmail(data: ReportData): Promise<ReportResult> {
    const html = this.generateReportHtml(data, false)

    return {
      success: true,
      format: 'html_email',
      html,
    }
  }

  /**
   * Generiert HTML für Report
   */
  private generateReportHtml(data: ReportData, forPdf: boolean): string {
    const styles = forPdf
      ? `
        body { font-family: 'Segoe UI', Arial, sans-serif; padding: 40px; color: #333; }
        h1 { color: #1a1a2e; border-bottom: 3px solid #4361ee; padding-bottom: 10px; }
        h2 { color: #4361ee; margin-top: 30px; }
        .metric-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin: 20px 0; }
        .metric { background: #f8f9fa; padding: 20px; border-radius: 8px; text-align: center; }
        .metric-value { font-size: 32px; font-weight: bold; color: #4361ee; }
        .metric-label { font-size: 14px; color: #666; margin-top: 5px; }
        table { width: 100%; border-collapse: collapse; margin: 20px 0; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #eee; }
        th { background: #f8f9fa; font-weight: 600; }
        .positive { color: #10b981; }
        .negative { color: #ef4444; }
        .neutral { color: #6b7280; }
      `
      : `
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; }
        h1 { color: #1a1a2e; font-size: 24px; }
        h2 { color: #4361ee; font-size: 18px; margin-top: 25px; }
        .metric-grid { display: flex; flex-wrap: wrap; gap: 15px; margin: 15px 0; }
        .metric { background: #f3f4f6; padding: 15px; border-radius: 8px; flex: 1; min-width: 120px; text-align: center; }
        .metric-value { font-size: 28px; font-weight: bold; color: #4361ee; }
        .metric-label { font-size: 12px; color: #666; }
        table { width: 100%; border-collapse: collapse; margin: 15px 0; font-size: 14px; }
        th, td { padding: 10px; text-align: left; border-bottom: 1px solid #e5e7eb; }
        th { background: #f9fafb; }
        .positive { color: #059669; }
        .negative { color: #dc2626; }
        .neutral { color: #6b7280; }
      `

    let html = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8">
        <style>${styles}</style>
      </head>
      <body>
        <h1>Community Report: ${data.schedule.name}</h1>
        <p style="color: #666;">
          Zeitraum: ${data.periodStart.toLocaleDateString('de-DE')} - ${data.periodEnd.toLocaleDateString('de-DE')}
          <br>Erstellt: ${data.generatedAt.toLocaleString('de-DE')}
        </p>
    `

    if (data.overview) {
      html += `
        <h2>Übersicht</h2>
        <div class="metric-grid">
          <div class="metric">
            <div class="metric-value">${data.overview.totalInteractions}</div>
            <div class="metric-label">Gesamt Interaktionen</div>
          </div>
          <div class="metric">
            <div class="metric-value">${data.overview.newInteractions}</div>
            <div class="metric-label">Neu</div>
          </div>
          <div class="metric">
            <div class="metric-value">${data.overview.repliedCount}</div>
            <div class="metric-label">Beantwortet</div>
          </div>
          <div class="metric">
            <div class="metric-value">${data.overview.avgResponseTime.toFixed(1)}h</div>
            <div class="metric-label">Ø Antwortzeit</div>
          </div>
        </div>
        <table>
          <tr><th>Plattform</th><th>Interaktionen</th></tr>
          ${data.overview.platforms.map((p) => `<tr><td>${p.platform}</td><td>${p.count}</td></tr>`).join('')}
        </table>
      `
    }

    if (data.sentimentAnalysis) {
      const total = data.sentimentAnalysis.positive + data.sentimentAnalysis.neutral + data.sentimentAnalysis.negative
      html += `
        <h2>Sentiment-Analyse</h2>
        <div class="metric-grid">
          <div class="metric">
            <div class="metric-value positive">${total > 0 ? ((data.sentimentAnalysis.positive / total) * 100).toFixed(0) : 0}%</div>
            <div class="metric-label">Positiv (${data.sentimentAnalysis.positive})</div>
          </div>
          <div class="metric">
            <div class="metric-value neutral">${total > 0 ? ((data.sentimentAnalysis.neutral / total) * 100).toFixed(0) : 0}%</div>
            <div class="metric-label">Neutral (${data.sentimentAnalysis.neutral})</div>
          </div>
          <div class="metric">
            <div class="metric-value negative">${total > 0 ? ((data.sentimentAnalysis.negative / total) * 100).toFixed(0) : 0}%</div>
            <div class="metric-label">Negativ (${data.sentimentAnalysis.negative})</div>
          </div>
        </div>
      `
    }

    if (data.responseMetrics) {
      html += `
        <h2>Antwort-Metriken</h2>
        <div class="metric-grid">
          <div class="metric">
            <div class="metric-value">${data.responseMetrics.avgResponseTimeHours.toFixed(1)}h</div>
            <div class="metric-label">Ø Antwortzeit</div>
          </div>
          <div class="metric">
            <div class="metric-value">${data.responseMetrics.responseRate.toFixed(0)}%</div>
            <div class="metric-label">Antwortrate</div>
          </div>
          <div class="metric">
            <div class="metric-value">${data.responseMetrics.pendingCount}</div>
            <div class="metric-label">Ausstehend</div>
          </div>
        </div>
      `
    }

    if (data.contentPerformance && data.contentPerformance.topPosts.length > 0) {
      html += `
        <h2>Top Content</h2>
        <table>
          <tr><th>Titel</th><th>Plattform</th><th>Kommentare</th></tr>
          ${data.contentPerformance.topPosts
            .slice(0, 5)
            .map((p) => `<tr><td>${p.title.substring(0, 50)}${p.title.length > 50 ? '...' : ''}</td><td>${p.platform}</td><td>${p.comments}</td></tr>`)
            .join('')}
        </table>
      `
    }

    html += `
        <hr style="margin-top: 30px; border: none; border-top: 1px solid #eee;">
        <p style="font-size: 12px; color: #999;">
          Dieser Report wurde automatisch generiert vom Community Management System.
        </p>
      </body>
      </html>
    `

    return html
  }

  private resolvePlatformName(platform: unknown): string {
    if (typeof platform === 'string') return platform
    if (typeof platform === 'number') return String(platform)
    if (platform && typeof platform === 'object') {
      const p = platform as { slug?: string; name?: string }
      return p.slug || p.name || 'unknown'
    }
    return 'unknown'
  }

  private resolveContentTitle(linkedContent: unknown, fallbackId: string): string {
    if (!linkedContent || typeof linkedContent !== 'object') return fallbackId
    const content = linkedContent as { title?: unknown }
    if (typeof content.title === 'string') return content.title
    if (content.title && typeof content.title === 'object') {
      const localized = content.title as { de?: string; en?: string }
      return localized.de || localized.en || fallbackId
    }
    return fallbackId
  }

  /**
   * Generiert einfachen E-Mail-Body für Attachments
   */
  private generateEmailBody(schedule: ReportSchedule): string {
    return `
      <html>
      <body style="font-family: Arial, sans-serif; padding: 20px;">
        <h2>Community Report: ${schedule.name}</h2>
        <p>Im Anhang finden Sie den automatisch generierten Community Report.</p>
        <p>
          <strong>Report-Typ:</strong> ${schedule.reportType}<br>
          <strong>Zeitraum:</strong> Letzte ${schedule.periodDays} Tage<br>
          <strong>Erstellt:</strong> ${new Date().toLocaleString('de-DE')}
        </p>
        <hr>
        <p style="font-size: 12px; color: #666;">
          Dieser Report wurde automatisch vom Community Management System versendet.
        </p>
      </body>
      </html>
    `
  }

  /**
   * Holt einen Schedule aus der Datenbank
   */
  private async getSchedule(id: number): Promise<{ sendCount: number } | null> {
    try {
      const schedule = await this.payload.findByID({
        collection: 'report-schedules',
        id,
      })
      return schedule as { sendCount: number }
    } catch {
      return null
    }
  }
}

export default ReportGeneratorService
