// import { Op } from 'sequelize';
// import transporter from '../config/mail.js';
// import { DomainManagement, User } from '../models/index.js';

// const ALERT_DAYS_BEFORE_EXPIRY = 7;
// const DAILY_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;

// const parseEmailList = (value) => {
//     if (!value) return [];

//     return value
//         .split(',')
//         .map((email) => email.trim().toLowerCase())
//         .filter(Boolean);
// };

// const uniqueEmails = (emails) => [...new Set(emails)];

// const escapeHtml = (value) => String(value ?? '')
//     .replace(/&/g, '&amp;')
//     .replace(/</g, '&lt;')
//     .replace(/>/g, '&gt;')
//     .replace(/"/g, '&quot;')
//     .replace(/'/g, '&#39;');

// const toDateOnly = (date) => {
//     const year = date.getFullYear();
//     const month = String(date.getMonth() + 1).padStart(2, '0');
//     const day = String(date.getDate()).padStart(2, '0');

//     return `${year}-${month}-${day}`;
// };

// const getTargetExpiryDate = () => {
//     const targetDate = new Date();
//     targetDate.setHours(0, 0, 0, 0);
//     targetDate.setDate(targetDate.getDate() + ALERT_DAYS_BEFORE_EXPIRY);
//     return toDateOnly(targetDate);
// };

// const getDaysLeft = (expiryDate) => {
//     const expiry = new Date(expiryDate);
//     expiry.setHours(0, 0, 0, 0);

//     const today = new Date();
//     today.setHours(0, 0, 0, 0);

//     return Math.ceil((expiry - today) / (1000 * 60 * 60 * 24));
// };

// const buildMailHtml = (domains) => {
//     const rows = domains.map((domain) => `
//         <tr>
//             <td style="padding:12px;border-bottom:1px solid #eef2f6;color:#374151;">${escapeHtml(domain.domain_name)}</td>
//             <td style="padding:12px;border-bottom:1px solid #eef2f6;color:#374151;">${escapeHtml(domain.client)}</td>
//             <td style="padding:12px;border-bottom:1px solid #eef2f6;color:#374151;">${escapeHtml(domain.registrar)}</td>
//             <td style="padding:12px;border-bottom:1px solid #eef2f6;color:#374151;">${escapeHtml(domain.expiry_date)}</td>
//         </tr>
//     `).join('');

//     return `
//         <div style="font-family:'Segoe UI',Arial,sans-serif;color:#1f2937;">
//             <h2>Domain Renewal Alert (Admin Overview)</h2>
//             <p>The following domain(s) will expire in ${ALERT_DAYS_BEFORE_EXPIRY} days:</p>
//             <table style="border-collapse:collapse;width:100%;max-width:760px;border:1px solid #e5e7eb;">
//                 <thead>
//                     <tr style="background-color:#f9fafb;">
//                         <th style="padding:12px;border-bottom:2px solid #e5e7eb;text-align:left;">Domain</th>
//                         <th style="padding:12px;border-bottom:2px solid #e5e7eb;text-align:left;">Client</th>
//                         <th style="padding:12px;border-bottom:2px solid #e5e7eb;text-align:left;">Registrar</th>
//                         <th style="padding:12px;border-bottom:2px solid #e5e7eb;text-align:left;">Expiry Date</th>
//                     </tr>
//                 </thead>
//                 <tbody>${rows}</tbody>
//             </table>
//         </div>
//     `;
// };


// const buildUserRenewalMailHtml = (domain, daysLeft, customCost = null) => {
//     const expiryText = daysLeft < 0
//         ? 'has expired'
//         : `will expire in <span style="color:#6366f1;font-weight:600;">${daysLeft} day${daysLeft === 1 ? '' : 's'}</span>`;
//     const displayCost = customCost !== null && customCost !== undefined && customCost !== ''
//         ? Number(customCost)
//         : Number(domain.cost || 0);

//     return `
//     <div style="background-color:#f8fafc;padding:30px 15px;font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;margin:0;">
//         <table align="center" border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width:600px;background-color:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 6px -1px rgba(0,0,0,0.05),0 2px 4px -1px rgba(0,0,0,0.03);border-collapse:collapse;">
            
//             <tr>
//                 <td style="background:linear-gradient(135deg, #0b0f2b 0%, #1e1b4b 60%, #4c1d95 100%);padding:30px;text-align:left;">
//                     <table border="0" cellpadding="0" cellspacing="0" width="100%">
//                         <tr>
//                             <td>
//                                 <table border="0" cellpadding="0" cellspacing="0">
//                                     <tr>
//                                         <td style="background-color:#ffffff;border-radius:8px;padding:6px 10px;font-weight:bold;color:#0b0f2b;font-size:20px;letter-spacing:0.5px;">
//                                             <span style="color:#6366f1;">D</span>eytal
//                                         </td>
//                                         <td style="padding-left:8px;vertical-align:bottom;padding-bottom:4px;color:#94a3b8;font-size:10px;font-family:sans-serif;text-transform:uppercase;letter-spacing:1px;">
//                                             Technologies Pvt Ltd
//                                         </td>
//                                     </tr>
//                                 </table>
//                             </td>
//                         </tr>
//                     </table>
//                 </td>
//             </tr>

//             <tr>
//                 <td style="padding:40px 35px 30px 35px;">
                    
//                     <table border="0" cellpadding="0" cellspacing="0" style="margin-bottom:24px;">
//                         <tr>
//                             <td style="background-color:#eff6ff;border-radius:50%;width:44px;height:44px;text-align:center;vertical-align:middle;">
//                                 <span style="color:#4f46e5;font-size:22px;line-height:44px;">🔔</span>
//                             </td>
//                             <td style="padding-left:16px;">
//                                 <h1 style="margin:0;font-size:24px;font-weight:700;color:#0f172a;letter-spacing:-0.5px;">Domain Renewal Reminder</h1>
//                             </td>
//                         </tr>
//                     </table>

//                     <div style="width:40px;height:3px;background-color:#6366f1;margin-bottom:28px;border-radius:2px;"></div>

//                     <p style="margin:0 0 16px 0;font-size:16px;color:#334155;">Hi,</p>
//                     <p style="margin:0 0 32px 0;font-size:15px;line-height:1.6;color:#475569;">
//                         Your domain <a href="http://${escapeHtml(domain.domain_name)}" style="color:#4f46e5;text-decoration:none;font-weight:600;">${escapeHtml(domain.domain_name)}</a> ${expiryText}. Please renew it before the expiry date to avoid service interruption.
//                     </p>

//                     <table border="0" cellpadding="0" cellspacing="0" width="100%" style="border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;border-collapse:separate;">
//                         <tbody>
//                             <tr style="background-color:#ffffff;">
//                                 <td style="padding:16px;width:35%;font-size:14px;font-weight:600;color:#334155;border-bottom:1px solid #e2e8f0;">Domain</td>
//                                 <td style="padding:16px;font-size:14px;color:#4f46e5;font-weight:600;border-bottom:1px solid #e2e8f0;">${escapeHtml(domain.domain_name)}</td>
//                             </tr>
//                             <tr style="background-color:#ffffff;">
//                                 <td style="padding:16px;font-size:14px;font-weight:600;color:#334155;border-bottom:1px solid #e2e8f0;">Client</td>
//                                 <td style="padding:16px;font-size:14px;color:#475569;border-bottom:1px solid #e2e8f0;">${escapeHtml(domain.client)}</td>
//                             </tr>
//                             <tr style="background-color:#ffffff;">
//                                 <td style="padding:16px;font-size:14px;font-weight:600;color:#334155;border-bottom:1px solid #e2e8f0;">Registrar</td>
//                                 <td style="padding:16px;font-size:14px;color:#475569;border-bottom:1px solid #e2e8f0;">${escapeHtml(domain.registrar)}</td>
//                             </tr>
//                             <tr style="background-color:#ffffff;">
//                                 <td style="padding:16px;font-size:14px;font-weight:600;color:#334155;border-bottom:1px solid #e2e8f0;">Cost</td>
//                                 <td style="padding:16px;font-size:14px;color:#475569;font-weight:500;border-bottom:1px solid #e2e8f0;">INR ${displayCost.toFixed(2)}</td>
//                             </tr>
//                             <tr style="background-color:#ffffff;">
//                                 <td style="padding:16px;font-size:14px;font-weight:600;color:#334155;">Expiry Date</td>
//                                 <td style="padding:16px;font-size:14px;color:#475569;font-weight:500;">${escapeHtml(domain.expiry_date)}</td>
//                             </tr>
//                         </tbody>
//                     </table>
//                 </td>
//             </tr>

//             <tr>
//                 <td style="padding:0 35px 35px 35px;">
//                     <div style="width:100%;height:1px;background-color:#e2e8f0;margin-bottom:25px;"></div>
//                     <table border="0" cellpadding="0" cellspacing="0" width="100%">
//                         <tr>
//                             <td style="vertical-align:middle;width:42px;">
//                                 <div style="background-color:#e0e7ff;border-radius:50%;width:36px;height:36px;text-align:center;vertical-align:middle;">
//                                     <span style="color:#4f46e5;font-size:18px;line-height:36px;">🛡️</span>
//                                 </div>
//                             </td>
//                             <td style="vertical-align:middle;padding-left:12px;">
//                                 <p style="margin:0 0 4px 0;font-size:13px;color:#64748b;font-weight:500;">Need help? Our support team is here for you.</p>
//                                 <p style="margin:0;font-size:13px;color:#4f46e5;font-weight:500;">
//                                     ✉️ <a href="mailto:support@deytal.io" style="color:#4f46e5;text-decoration:none;margin-right:15px;">support@deytal.io</a>
//                                     <span style="color:#cbd5e1;margin-right:15px;">|</span>
//                                     🎧 24/7 Support
//                                 </p>
//                             </td>
//                         </tr>
//                     </table>
//                 </td>
//             </tr>
//         </table>
//     </div>
//     `;
// };

// export const sendDomainRenewalAlertToUser = async (domain, customCost = null) => {
//     const recipient = domain.email?.trim().toLowerCase();

//     if (!recipient) {
//         return {
//             sent: false,
//             message: 'No user email found for this domain'
//         };
//     }

//     const parsedCost = customCost === null || customCost === undefined || customCost === ''
//         ? null
//         : Number(customCost);

//     const emailDomain = {
//         ...domain.toJSON(),
//         cost: parsedCost !== null ? parsedCost : domain.cost
//     };

//     const daysLeft = getDaysLeft(domain.expiry_date);
//     const dayText = daysLeft < 0
//         ? 'expired'
//         : `expires in ${daysLeft} day${daysLeft === 1 ? '' : 's'}`;

//     await transporter.sendMail({
//         from: process.env.EMAIL_USER,
//         to: recipient,
//         subject: `Domain renewal reminder: ${domain.domain_name} ${dayText}`,
//         html: buildUserRenewalMailHtml(emailDomain, daysLeft, parsedCost)
//     });

//     await domain.update({
//         renewal_alert_sent_at: new Date(),
//         renewal_alert_for_expiry: domain.expiry_date
//     });

//     return {
//         sent: true,
//         message: 'Domain renewal email sent to user',
//         recipient
//     };
// };

// export const sendDomainRenewalAlerts = async () => {
//     const targetExpiryDate = getTargetExpiryDate();

//     const domains = await DomainManagement.findAll({
//         where: {
//             expiry_date: targetExpiryDate,
//             status: {
//                 [Op.ne]: 'expired'
//             },
//             [Op.or]: [
//                 { renewal_alert_for_expiry: null },
//                 { renewal_alert_for_expiry: { [Op.ne]: targetExpiryDate } }
//             ]
//         },
//         order: [['expiry_date', 'ASC']]
//     });

//     if (!domains.length) {
//         return {
//             sent: false,
//             message: 'No domain renewal alerts due today',
//             totalDomains: 0
//         };
//     }

//     const configuredRecipients = parseEmailList(process.env.DOMAIN_RENEWAL_ALERT_EMAILS);
//     let recipients = configuredRecipients;

//     if (!recipients.length) {
//         const admins = await User.findAll({
//             where: {
//                 role: 'admin',
//                 status: 'active'
//             },
//             attributes: ['email']
//         });

//         const senderEmail = process.env.EMAIL_USER?.trim().toLowerCase();
//         recipients = admins
//             .map((admin) => admin.email?.trim().toLowerCase())
//             .filter((email) => email && email !== senderEmail);
//     }

//     recipients = uniqueEmails(recipients);

//     if (!recipients.length) {
//         return {
//             sent: false,
//             message: 'No renewal alert recipient email found',
//             totalDomains: domains.length
//         };
//     }

//     await transporter.sendMail({
//         from: process.env.EMAIL_USER,
//         to: recipients.join(','),
//         subject: `Domain renewal alert: ${domains.length} domain(s) expire in ${ALERT_DAYS_BEFORE_EXPIRY} days`,
//         html: buildMailHtml(domains)
//     });

//     await Promise.all(domains.map((domain) => domain.update({
//         renewal_alert_sent_at: new Date(),
//         renewal_alert_for_expiry: targetExpiryDate
//     })));

//     return {
//         sent: true,
//         message: 'Domain renewal alert email sent',
//         totalDomains: domains.length,
//         recipients
//     };
// };

// export const startDomainRenewalAlertScheduler = () => {
//     sendDomainRenewalAlerts().catch((error) => {
//         console.log('Domain renewal alert error:', error);
//     });

//     setInterval(() => {
//         sendDomainRenewalAlerts().catch((error) => {
//             console.log('Domain renewal alert error:', error);
//         });
//     }, DAILY_CHECK_INTERVAL_MS);
// };


import { Op } from 'sequelize';
import transporter from '../config/mail.js';
import { DomainManagement, User } from '../models/index.js';
import { buildMailHtml, buildUserRenewalMailHtml } from '../templates/domainRenewalTemp.js';

const ALERT_DAYS_BEFORE_EXPIRY = 7;
const DAILY_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;

const parseEmailList = (value) => {
    if (!value) return [];

    return value
        .split(',')
        .map((email) => email.trim().toLowerCase())
        .filter(Boolean);
};

const uniqueEmails = (emails) => [...new Set(emails)];

const toDateOnly = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
};

const getTargetExpiryDate = () => {
    const targetDate = new Date();
    targetDate.setHours(0, 0, 0, 0);
    targetDate.setDate(targetDate.getDate() + ALERT_DAYS_BEFORE_EXPIRY);
    return toDateOnly(targetDate);
};

const getDaysLeft = (expiryDate) => {
    const expiry = new Date(expiryDate);
    expiry.setHours(0, 0, 0, 0);

    const today = new Date();
    today.setHours(0, 0, 0, 0);

    return Math.ceil((expiry - today) / (1000 * 60 * 60 * 24));
};

export const sendDomainRenewalAlertToUser = async (domain, customCost = null, customMessageHtml = null) => {
   const recipient = domain.client_email?.trim().toLowerCase();

    if (!recipient) {
        return {
            sent: false,
            message: 'No user email found for this domain'
        };
    }

    const parsedCost = customCost === null || customCost === undefined || customCost === ''
        ? null
        : Number(customCost);

    const emailDomain = {
        ...domain.toJSON(),
        cost: parsedCost !== null ? parsedCost : domain.cost
    };

    const daysLeft = getDaysLeft(domain.expiry_date);
    const dayText = daysLeft < 0
        ? 'expired'
        : `expires in ${daysLeft} day${daysLeft === 1 ? '' : 's'}`;

    await transporter.sendMail({
        from: process.env.EMAIL_USER,
        to: recipient,
        subject: `Domain renewal reminder: ${domain.domain_name} ${dayText}`,
        html: buildUserRenewalMailHtml(emailDomain, daysLeft, customMessageHtml)
    });

    await domain.update({
        renewal_alert_sent_at: new Date(),
        renewal_alert_for_expiry: domain.expiry_date
    });

    return {
        sent: true,
        message: 'Domain renewal email sent to user',
        recipient
    };
};

export const sendDomainRenewalAlerts = async () => {
    const targetExpiryDate = getTargetExpiryDate();

    const domains = await DomainManagement.findAll({
        where: {
            expiry_date: targetExpiryDate,
            status: {
                [Op.ne]: 'expired'
            },
            [Op.or]: [
                { renewal_alert_for_expiry: null },
                { renewal_alert_for_expiry: { [Op.ne]: targetExpiryDate } }
            ]
        },
        order: [['expiry_date', 'ASC']]
    });

    if (!domains.length) {
        return {
            sent: false,
            message: 'No domain renewal alerts due today',
            totalDomains: 0
        };
    }

    const configuredRecipients = parseEmailList(process.env.DOMAIN_RENEWAL_ALERT_EMAILS);
    let recipients = configuredRecipients;

    if (!recipients.length) {
        const admins = await User.findAll({
            where: {
                role: 'admin',
                status: 'active'
            },
            attributes: ['email']
        });

        const senderEmail = process.env.EMAIL_USER?.trim().toLowerCase();
        recipients = admins
            .map((admin) => admin.email?.trim().toLowerCase())
            .filter((email) => email && email !== senderEmail);
    }

    recipients = uniqueEmails(recipients);

    if (!recipients.length) {
        return {
            sent: false,
            message: 'No renewal alert recipient email found',
            totalDomains: domains.length
        };
    }

    await transporter.sendMail({
        from: process.env.EMAIL_USER,
        to: recipients.join(','),
        subject: `Domain renewal alert: ${domains.length} domain(s) expire in ${ALERT_DAYS_BEFORE_EXPIRY} days`,
        html: buildMailHtml(domains)
    });

    await Promise.all(domains.map((domain) => domain.update({
        renewal_alert_sent_at: new Date(),
        renewal_alert_for_expiry: targetExpiryDate
    })));

    return {
        sent: true,
        message: 'Domain renewal alert email sent',
        totalDomains: domains.length,
        recipients
    };
};

export const startDomainRenewalAlertScheduler = () => {
    sendDomainRenewalAlerts().catch((error) => {
        console.log('Domain renewal alert error:', error);
    });

    setInterval(() => {
        sendDomainRenewalAlerts().catch((error) => {
            console.log('Domain renewal alert error:', error);
        });
    }, DAILY_CHECK_INTERVAL_MS);
};
