import { Injectable, Logger } from '@nestjs/common';
import { Alert } from '../entity/alert.entity';
import { NewsletterService } from 'modules/newsletter/news-letter.service';
import { INewsletterSendOptions } from 'modules/newsletter/interface/Inewsletter.interface';
import { SendTo } from 'common/enum/HostType.enum';

@Injectable()
export class AlertPublisherService {
  private readonly logger = new Logger(AlertPublisherService.name);

  constructor(private newsletterService: NewsletterService) {}

  // Send an alert to the newsletter system
  async sendToNewsletter(alert: Alert): Promise<string> {
    try {
      this.logger.log(`Sending alert to newsletter: ${alert.id}`);

      // Format the alert data for the newsletter system
      const newsletterData = this.formatAlertForNewsletter(alert);

      this.logger.log(`Alert data formatted for newsletter: ${JSON.stringify(newsletterData)}`);
      // Send the alert to the newsletter system
      const response = await this.newsletterService.sendNewsletter(newsletterData);

      this.logger.log(`Alert sent to newsletter: ${alert.id}`);
      return response;
    } catch (error) {
      this.logger.error(`Error sending alert to newsletter: ${error.message}`);
      throw error;
    }
  }

  // Format the alert data for the newsletter system
  private formatAlertForNewsletter(alert: Alert): any {
    // Determine the severity level string
    let severityLevel = 'Medium';
    let severityColor = 'ffcc00'; // Default color (yellow)
    if (alert.severity >= 4) {
      severityLevel = 'High';
      severityColor = 'ff6600'; // Orange
    } else if (alert.severity <= 2) {
      severityLevel = 'Low';
      severityColor = '66cc00'; // Light Green
    }

    // Create newsletter content
    const content = `
            <div style="border-left: 4px solid #${severityColor}; padding-left: 15px; margin-bottom: 20px;">
                <h2>${alert.title}</h2>
                <p><strong>Severity:</strong> ${severityLevel}</p>
                <p><strong>Target Organization:</strong> ${alert.targetOrganization} (${alert.targetCountry})</p>
                <p><strong>Attack Type:</strong> ${alert.attackType}</p>
                <p><strong>Attack Date:</strong> ${alert.attackTime ? new Date(alert.attackTime).toLocaleDateString() : 'Unknown'}</p>
                <div style="margin-top: 15px;">
                    <p>${alert.description}</p>
                </div>
                <div style="margin-top: 10px; font-size: 0.9em; color: #666;">
                    <p>Source: ${alert.source} ${alert.sourceUrl ? `<a href="${alert.sourceUrl}" target="_blank">(View Source)</a>` : ''}</p>
                </div>
                <!-- Adding metadata fields to the content -->
                <div style="margin-top: 20px; padding-top: 10px; border-top: 1px solid #ccc;">
                    <h3>Alert Metadata</h3>
                    <ul>
                        <li><strong>Alert ID:</strong> ${alert.id}</li>
                        <li><strong>Severity:</strong> ${alert.severity}</li>
                        <li><strong>Relevant to Nepal:</strong> ${alert.isRelevantToNepal ? 'Yes' : 'No'}</li>
                        <li><strong>Created At:</strong> ${alert.createdAt ? new Date(alert.createdAt).toLocaleString() : 'Unknown'}</li>
                    </ul>
                </div>
            </div>
        `;

    // Create the newsletter object
    const newsletter: INewsletterSendOptions = {
      subject: `[CYBER ALERT] ${severityLevel} Severity: ${alert.title}`,
      body: content, // Send the HTML-formatted content
      sendTo: SendTo.ALL, // Target all users, you can customize based on your needs
      customEmails: [], // Add custom emails if needed
    };

    return newsletter;
  }
}
