import { logger } from '../utils/logger';
import nodemailer from 'nodemailer';

interface EmailOptions {
  to: string;
  bcc?: string[];
  subject: string;
  html: string;
}

export class EmailService {
  private static instance: EmailService;
  private transporter: nodemailer.Transporter;

  private constructor() {
    // Initialize Gmail SMTP transporter
    this.transporter = nodemailer.createTransport({
      host: process.env['SMTP_HOST'] || 'smtp.gmail.com',
      port: parseInt(process.env['SMTP_PORT'] || '587'),
      secure: process.env['SMTP_SECURE'] === 'true', // false for 587, true for 465
      auth: {
        user: process.env['GOOGLE_EMAIL'],
        pass: process.env['GOOGLE_APP_PASSWORD'],
      },
    });

    // Verify SMTP connection
    this.verifyConnection();
  }

  public static getInstance(): EmailService {
    if (!EmailService.instance) {
      EmailService.instance = new EmailService();
    }
    return EmailService.instance;
  }

  private async verifyConnection(): Promise<void> {
    try {
      await this.transporter.verify();
      logger.info('SMTP connection verified successfully');
    } catch (error) {
      logger.error('SMTP connection failed:', error);
    }
  }

  async sendEmail(options: EmailOptions): Promise<boolean> {
    try {
      const mailOptions: any = {
        from: {
          name: 'Court Docket System',
          address: process.env['GOOGLE_EMAIL'] || 'system@deafgain.org',
        },
        to: options.to,
        subject: options.subject,
        html: options.html,
      };

      // Add BCC if provided
      if (options.bcc && options.bcc.length > 0) {
        mailOptions.bcc = options.bcc;
      }

      const result = await this.transporter.sendMail(mailOptions);
      
      logger.info('Email sent successfully:', {
        to: options.to,
        bcc: options.bcc ? `${options.bcc.length} recipients` : 'none',
        subject: options.subject,
        messageId: result.messageId,
      });

      return true;
    } catch (error) {
      logger.error('Failed to send email:', error);
      return false;
    }
  }

  async notifySubscribersOfNewEntry(entryTitle: string, entryDate: string, entrySummary: string): Promise<void> {
    try {
      // Get all active subscribers
      const { prisma } = await import('../index');
      const subscribers = await prisma.subscription.findMany({
        where: { isActive: true },
      });

      if (subscribers.length === 0) {
        logger.info('No active subscribers to notify');
        return;
      }

      const subject = `New Court Filing: ${entryTitle}`;
      const html = this.generateNotificationEmail(entryTitle, entryDate, entrySummary);
      const subscriberEmails = subscribers.map((subscriber: any) => subscriber.email);

      // Send single email with all subscribers as BCC
      const success = await this.sendEmail({
        to: process.env['GOOGLE_EMAIL'] || 'system@deafgain.org',
        bcc: subscriberEmails,
        subject,
        html,
      });

      if (success) {
        logger.info(`Email notification sent successfully to ${subscriberEmails.length} subscribers via BCC`);
      } else {
        logger.error(`Failed to send BCC email notification to ${subscriberEmails.length} subscribers`);
      }
    } catch (error) {
      logger.error('Failed to notify subscribers:', error);
    }
  }

  private generateNotificationEmail(title: string, date: string, summary: string): string {
    const formattedDate = new Date(date).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });

    return `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>New Court Filing Notification</title>
        <style>
          body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
          }
          .header {
            background-color: #1f2937;
            color: white;
            padding: 20px;
            text-align: center;
            border-radius: 8px 8px 0 0;
          }
          .content {
            background-color: #f9fafb;
            padding: 30px;
            border-radius: 0 0 8px 8px;
            border: 1px solid #e5e7eb;
          }
          .filing-info {
            background-color: white;
            padding: 20px;
            border-radius: 6px;
            margin: 20px 0;
            border-left: 4px solid #3b82f6;
          }
          .date {
            color: #6b7280;
            font-size: 14px;
            margin-bottom: 10px;
          }
          .title {
            font-size: 18px;
            font-weight: bold;
            color: #1f2937;
            margin-bottom: 15px;
          }
          .summary {
            color: #4b5563;
            line-height: 1.5;
          }
          .footer {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e5e7eb;
            font-size: 12px;
            color: #6b7280;
            text-align: center;
          }
          .button {
            display: inline-block;
            background-color: #3b82f6;
            color: white;
            padding: 12px 24px;
            text-decoration: none;
            border-radius: 6px;
            margin: 20px 0;
          }
        </style>
      </head>
      <body>
        <div class="header">
          <h1>Eliza Kragh v. Montana Association of the Deaf</h1>
          <p>New Court Filing Notification</p>
        </div>
        
        <div class="content">
          <p>A new filing has been added to the court docket:</p>
          
          <div class="filing-info">
            <div class="date">${formattedDate}</div>
            <div class="title">${title}</div>
            <div class="summary">${summary}</div>
          </div>
          
          <p>You can view the complete docket and any associated documents by visiting the <a href="https://mad-lawsuit.org/" style="color: #3b82f6; text-decoration: none;">website</a>:</p>
          
          <a href="https://mad-lawsuit.org/" class="button">
            View Court Docket
          </a>
          
          <div class="footer">
            <p>You are receiving this email because you subscribed to notifications for this case.</p>
            <p>This is an automated notification from the court docket system.</p>
            <p>To unsubscribe, please send an email to eliza.kragh@gmail.com</p>
          </div>
        </div>
      </body>
      </html>
    `;
  }
}

export const emailService = EmailService.getInstance();
