import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AppMailerService } from './mailer.service';

export interface SentMessage {
  name: string;
  phone: string;
  category: string;
}

export interface CronJobReport {
  jobName: string;
  startTime: Date;
  endTime: Date;
  duration: number; // en millisecondes
  status: 'success' | 'error';
  error?: string;
  statistics?: Record<string, unknown>;
  details?: string;
  sentMessages?: SentMessage[];
}

@Injectable()
export class CronReportService {
  private readonly logger = new Logger(CronReportService.name);
  private readonly reportRecipients: string[];

  constructor(
    private readonly mailerService: AppMailerService,
    private readonly configService: ConfigService,
  ) {
    // Récupérer les destinataires depuis les variables d'environnement
    // Format attendu: "email1@example.com,email2@example.com" ou un seul email
    const recipientsEnv = process.env.CRON_REPORT_RECIPIENTS || 'ethan.fajnkuchen@ad-plus.tech';
    this.reportRecipients = recipientsEnv.split(',').map(email => email.trim());
    this.logger.log(`Cron report recipients: ${this.reportRecipients.join(', ')}`);
  }

  /**
   * Envoie un compte-rendu par email pour un cron job
   */
  async sendReport(report: CronJobReport): Promise<void> {
    try {
      const apiUrl = this.configService.get<string>('API_URL') || 
                     this.configService.get<string>('SERVER_URL') || 
                     'N/A';
      const subject = `[AD+ DMLA] Compte-rendu Cron Job: ${report.jobName} - ${report.status === 'success' ? '✅ Succès' : '❌ Erreur'} - ${apiUrl}`;
      const html = this.generateReportHtml(report);
      const text = this.generateReportText(report);

      await this.mailerService.sendMail({
        to: this.reportRecipients,
        subject,
        text,
        html,
      });

      this.logger.log(`Cron report sent successfully for job: ${report.jobName}`);
    } catch (error) {
      this.logger.error(`Error sending cron report for job ${report.jobName}:`, error);
      // Ne pas throw pour éviter de casser le cron job si l'envoi d'email échoue
    }
  }

  /**
   * Génère le HTML du compte-rendu
   */
  private generateReportHtml(report: CronJobReport): string {
    const statusEmoji = report.status === 'success' ? '✅' : '❌';
    const statusColor = report.status === 'success' ? '#28a745' : '#dc3545';
    const durationSeconds = (report.duration / 1000).toFixed(2);

    let statisticsHtml = '';
    if (report.statistics && Object.keys(report.statistics).length > 0) {
      statisticsHtml = `
        <h3 style="color: #333; margin-top: 20px;">📊 Statistiques</h3>
        <table style="width: 100%; border-collapse: collapse; margin-top: 10px;">
          <tbody>
            ${Object.entries(report.statistics)
              .map(
                ([key, value]) => `
              <tr>
                <td style="padding: 8px; border-bottom: 1px solid #eee; font-weight: bold; width: 40%;">${this.formatKey(key)}</td>
                <td style="padding: 8px; border-bottom: 1px solid #eee;">${this.formatValue(value)}</td>
              </tr>
            `,
              )
              .join('')}
          </tbody>
        </table>
      `;
    }

    let errorHtml = '';
    if (report.error) {
      errorHtml = `
        <div style="background-color: #f8d7da; border: 1px solid #f5c6cb; border-radius: 4px; padding: 15px; margin-top: 20px;">
          <h3 style="color: #721c24; margin-top: 0;">❌ Erreur</h3>
          <pre style="color: #721c24; white-space: pre-wrap; word-wrap: break-word; margin: 0;">${this.escapeHtml(report.error)}</pre>
        </div>
      `;
    }

    let detailsHtml = '';
    if (report.details) {
      detailsHtml = `
        <div style="background-color: #d1ecf1; border: 1px solid #bee5eb; border-radius: 4px; padding: 15px; margin-top: 20px;">
          <h3 style="color: #0c5460; margin-top: 0;">ℹ️ Détails</h3>
          <pre style="color: #0c5460; white-space: pre-wrap; word-wrap: break-word; margin: 0;">${this.escapeHtml(report.details)}</pre>
        </div>
      `;
    }

    let sentMessagesHtml = '';
    if (report.sentMessages && report.sentMessages.length > 0) {
      sentMessagesHtml = `
        <h3 style="color: #333; margin-top: 20px;">📨 Liste des envois (${report.sentMessages.length})</h3>
        <table style="width: 100%; border-collapse: collapse; margin-top: 10px; border: 1px solid #ddd;">
          <thead>
            <tr style="background-color: #f8f9fa;">
              <th style="padding: 12px; text-align: left; border-bottom: 2px solid #ddd; font-weight: bold;">Nom</th>
              <th style="padding: 12px; text-align: left; border-bottom: 2px solid #ddd; font-weight: bold;">Téléphone</th>
              <th style="padding: 12px; text-align: left; border-bottom: 2px solid #ddd; font-weight: bold;">Catégorie</th>
            </tr>
          </thead>
          <tbody>
            ${report.sentMessages
              .map(
                (msg, index) => `
              <tr style="${index % 2 === 0 ? 'background-color: #ffffff;' : 'background-color: #f8f9fa;'}">
                <td style="padding: 10px; border-bottom: 1px solid #eee;">${this.escapeHtml(msg.name)}</td>
                <td style="padding: 10px; border-bottom: 1px solid #eee;">${this.escapeHtml(msg.phone)}</td>
                <td style="padding: 10px; border-bottom: 1px solid #eee;">${this.escapeHtml(msg.category)}</td>
              </tr>
            `,
              )
              .join('')}
          </tbody>
        </table>
      `;
    }

    return `
      <!DOCTYPE html>
      <html>
        <head>
          <meta charset="UTF-8">
          <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
          </style>
        </head>
        <body>
          <div style="max-width: 800px; margin: 0 auto; padding: 20px;">
            <h1 style="color: #333; border-bottom: 2px solid ${statusColor}; padding-bottom: 10px;">
              ${statusEmoji} Compte-rendu Cron Job: ${this.escapeHtml(report.jobName)}
            </h1>
            
            <div style="background-color: #f8f9fa; border-radius: 4px; padding: 15px; margin-top: 20px;">
              <table style="width: 100%;">
                <tr>
                  <td style="padding: 8px; font-weight: bold; width: 30%;">Statut:</td>
                  <td style="padding: 8px; color: ${statusColor}; font-weight: bold;">${report.status === 'success' ? 'Succès' : 'Erreur'}</td>
                </tr>
                <tr>
                  <td style="padding: 8px; font-weight: bold;">Date de début:</td>
                  <td style="padding: 8px;">${report.startTime.toLocaleString('fr-FR', { timeZone: 'Europe/Paris' })}</td>
                </tr>
                <tr>
                  <td style="padding: 8px; font-weight: bold;">Date de fin:</td>
                  <td style="padding: 8px;">${report.endTime.toLocaleString('fr-FR', { timeZone: 'Europe/Paris' })}</td>
                </tr>
                <tr>
                  <td style="padding: 8px; font-weight: bold;">Durée d'exécution:</td>
                  <td style="padding: 8px;">${durationSeconds} secondes</td>
                </tr>
              </table>
            </div>

            ${statisticsHtml}
            ${detailsHtml}
            ${sentMessagesHtml}
            ${errorHtml}

            <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; color: #666; font-size: 12px;">
              <p>Ce message a été généré automatiquement par le système AD+ DMLA.</p>
            </div>
          </div>
        </body>
      </html>
    `;
  }

  /**
   * Génère le texte brut du compte-rendu
   */
  private generateReportText(report: CronJobReport): string {
    const statusEmoji = report.status === 'success' ? '✅' : '❌';
    const durationSeconds = (report.duration / 1000).toFixed(2);

    let text = `
${statusEmoji} Compte-rendu Cron Job: ${report.jobName}

Statut: ${report.status === 'success' ? 'Succès' : 'Erreur'}
Date de début: ${report.startTime.toLocaleString('fr-FR', { timeZone: 'Europe/Paris' })}
Date de fin: ${report.endTime.toLocaleString('fr-FR', { timeZone: 'Europe/Paris' })}
Durée d'exécution: ${durationSeconds} secondes
`;

    if (report.statistics && Object.keys(report.statistics).length > 0) {
      text += '\n📊 Statistiques:\n';
      for (const [key, value] of Object.entries(report.statistics)) {
        text += `  - ${this.formatKey(key)}: ${this.formatValue(value)}\n`;
      }
    }

    if (report.details) {
      text += `\nℹ️ Détails:\n${report.details}\n`;
    }

    if (report.sentMessages && report.sentMessages.length > 0) {
      text += `\n📨 Liste des envois (${report.sentMessages.length}):\n`;
      text += `${'─'.repeat(80)}\n`;
      text += `${'Nom'.padEnd(25)} | ${'Téléphone'.padEnd(20)} | Catégorie\n`;
      text += `${'─'.repeat(80)}\n`;
      for (const msg of report.sentMessages) {
        text += `${msg.name.padEnd(25)} | ${msg.phone.padEnd(20)} | ${msg.category}\n`;
      }
      text += `${'─'.repeat(80)}\n`;
    }

    if (report.error) {
      text += `\n❌ Erreur:\n${report.error}\n`;
    }

    text += '\n---\nCe message a été généré automatiquement par le système AD+ DMLA.';

    return text;
  }

  /**
   * Formate une clé pour l'affichage
   */
  private formatKey(key: string): string {
    return key
      .replace(/([A-Z])/g, ' $1')
      .replace(/^./, (str) => str.toUpperCase())
      .trim();
  }

  /**
   * Formate une valeur pour l'affichage
   */
  private formatValue(value: unknown): string {
    if (value === null || value === undefined) {
      return 'N/A';
    }
    if (typeof value === 'object') {
      return JSON.stringify(value, null, 2);
    }
    return String(value);
  }

  /**
   * Échappe le HTML pour éviter les injections
   */
  private escapeHtml(text: string): string {
    const map: Record<string, string> = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#039;',
    };
    return text.replace(/[&<>"']/g, (m) => map[m]);
  }
}

