const emailService = require('../services/email');
const nocoDB = require('../services/nocodb');

class EmailsController {
  async sendEmail(req, res, next) {
    try {
      const { recipientEmail, senderName, senderEmail, subject, message, postalCode, recipientName } = req.body;
      
      // Send the email using template system
      const emailResult = await emailService.sendRepresentativeEmail(
        recipientEmail,
        senderName,
        senderEmail,
        subject,
        message,
        postalCode,
        recipientName
      );

      // Log the email send event
      await nocoDB.logEmailSend({
        recipientEmail,
        senderName,
        senderEmail,
        subject,
        message,
        postalCode,
        status: emailResult.success ? 'sent' : 'failed',
        timestamp: new Date().toISOString(),
        senderIP: req.ip || req.connection.remoteAddress
      });

      if (emailResult.success) {
        res.json({
          success: true,
          message: 'Email sent successfully',
          messageId: emailResult.messageId
        });
      } else {
        res.status(500).json({
          success: false,
          error: 'Failed to send email',
          message: emailResult.error
        });
      }
    } catch (error) {
      console.error('Send email error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to send email',
        message: error.message
      });
    }
  }

  async previewEmail(req, res, next) {
    try {
      const { recipientEmail, subject, message, senderName, senderEmail, postalCode, recipientName } = req.body;
      
      const templateVariables = {
        MESSAGE: message,
        SENDER_NAME: senderName || 'Anonymous',
        SENDER_EMAIL: senderEmail || 'unknown@example.com',
        POSTAL_CODE: postalCode || 'Unknown',
        RECIPIENT_NAME: recipientName || 'Representative'
      };

      const emailOptions = {
        to: recipientEmail,
        from: {
          email: process.env.SMTP_FROM_EMAIL,
          name: process.env.SMTP_FROM_NAME
        },
        replyTo: senderEmail || process.env.SMTP_FROM_EMAIL,
        subject: subject
      };

      const preview = await emailService.previewTemplatedEmail('representative-contact', templateVariables, emailOptions);
      
      // Log the email preview event (non-blocking)
      try {
        await nocoDB.logEmailPreview({
          recipientEmail,
          senderName,
          senderEmail,
          subject,
          message,
          postalCode,
          timestamp: new Date().toISOString(),
          senderIP: req.ip || req.connection.remoteAddress
        });
      } catch (loggingError) {
        console.error('Failed to log email preview:', loggingError);
        // Don't fail the preview if logging fails
      }
      
      res.json({
        success: true,
        preview: preview,
        html: emailOptions.html
      });
    } catch (error) {
      console.error('Email preview error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to generate email preview',
        message: error.message
      });
    }
  }

  async sendTestEmail(req, res, next) {
    try {
      const { subject, message } = req.body;
      
      const testRecipient = process.env.TEST_EMAIL_RECIPIENT || req.user?.email || 'admin@example.com';
      
      const emailResult = await emailService.sendTestEmail(subject, message, testRecipient);

      if (emailResult.success) {
        res.json({
          success: true,
          message: 'Test email sent successfully',
          messageId: emailResult.messageId,
          sentTo: testRecipient,
          testMode: emailResult.testMode
        });
      } else {
        res.status(500).json({
          success: false,
          error: 'Failed to send test email',
          message: emailResult.error
        });
      }
    } catch (error) {
      console.error('Send test email error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to send test email',
        message: error.message
      });
    }
  }

  async getEmailLogs(req, res, next) {
    try {
      const { status, senderEmail, postalCode } = req.query;
      
      if (!process.env.NOCODB_TABLE_EMAILS) {
        return res.status(500).json({
          success: false,
          error: 'Email logging not configured'
        });
      }

      const filters = {};
      if (status) filters.status = status;
      if (senderEmail) filters.senderEmail = senderEmail;
      if (postalCode) filters.postalCode = postalCode;

      const logs = await nocoDB.getEmailLogs(filters);

      res.json({
        success: true,
        logs: logs || []
      });
    } catch (error) {
      console.error('Get email logs error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to retrieve email logs',
        message: error.message
      });
    }
  }

  async testSMTPConnection(req, res, next) {
    try {
      const testResult = await emailService.testConnection();
      
      res.json({
        success: testResult.success,
        message: testResult.message,
        error: testResult.error
      });
    } catch (error) {
      console.error('SMTP test error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to test SMTP connection',
        message: error.message
      });
    }
  }

  async testSMTPConnection(req, res, next) {
    try {
      const result = await emailService.testConnection();
      
      res.json({
        success: result.success,
        message: result.message,
        error: result.error
      });
    } catch (error) {
      console.error('SMTP test error:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to test SMTP connection',
        message: error.message
      });
    }
  }
}

module.exports = new EmailsController();