"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.emailService = exports.EmailService = void 0;
const logger_1 = require("../utils/logger");
const nodemailer_1 = __importDefault(require("nodemailer"));
class EmailService {
    static instance;
    transporter;
    constructor() {
        this.transporter = nodemailer_1.default.createTransport({
            host: process.env['SMTP_HOST'] || 'smtp.gmail.com',
            port: parseInt(process.env['SMTP_PORT'] || '587'),
            secure: process.env['SMTP_SECURE'] === 'true',
            auth: {
                user: process.env['GOOGLE_EMAIL'],
                pass: process.env['GOOGLE_APP_PASSWORD'],
            },
        });
        this.verifyConnection();
    }
    static getInstance() {
        if (!EmailService.instance) {
            EmailService.instance = new EmailService();
        }
        return EmailService.instance;
    }
    async verifyConnection() {
        try {
            await this.transporter.verify();
            logger_1.logger.info('SMTP connection verified successfully');
        }
        catch (error) {
            logger_1.logger.error('SMTP connection failed:', error);
        }
    }
    async sendEmail(options) {
        try {
            const mailOptions = {
                from: {
                    name: 'Court Docket System',
                    address: process.env['GOOGLE_EMAIL'] || 'system@deafgain.org',
                },
                to: options.to,
                subject: options.subject,
                html: options.html,
            };
            if (options.bcc && options.bcc.length > 0) {
                mailOptions.bcc = options.bcc;
            }
            const result = await this.transporter.sendMail(mailOptions);
            logger_1.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_1.logger.error('Failed to send email:', error);
            return false;
        }
    }
    async notifySubscribersOfNewEntry(entryTitle, entryDate, entrySummary) {
        try {
            const { prisma } = await Promise.resolve().then(() => __importStar(require('../index')));
            const subscribers = await prisma.subscription.findMany({
                where: { isActive: true },
            });
            if (subscribers.length === 0) {
                logger_1.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) => subscriber.email);
            const success = await this.sendEmail({
                to: process.env['GOOGLE_EMAIL'] || 'system@deafgain.org',
                bcc: subscriberEmails,
                subject,
                html,
            });
            if (success) {
                logger_1.logger.info(`Email notification sent successfully to ${subscriberEmails.length} subscribers via BCC`);
            }
            else {
                logger_1.logger.error(`Failed to send BCC email notification to ${subscriberEmails.length} subscribers`);
            }
        }
        catch (error) {
            logger_1.logger.error('Failed to notify subscribers:', error);
        }
    }
    generateNotificationEmail(title, date, summary) {
        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>
    `;
    }
}
exports.EmailService = EmailService;
exports.emailService = EmailService.getInstance();
//# sourceMappingURL=emailService.js.map