const nodemailer = require('nodemailer');
const axios = require('axios');
const { getCompanyProfile } = require('../config/db');

class NotificationService {
  /**
   * Fetches the latest company configuration from the database
   */
  async getCompanyConfig() {
    const profile = await getCompanyProfile();
    return profile || {};
  }

  /**
   * Send an email using SMTP settings from the database
   * @param {string} to 
   * @param {string} subject 
   * @param {string} html 
   */
  async sendEmail(to, subject, html) {
    try {
      const config = await this.getCompanyConfig();
      
      if (!config.mail_host || !config.mail_username || !config.mail_password) {
        console.warn('Mail configuration is missing or incomplete.');
        return { success: false, message: 'Mail configuration incomplete.' };
      }

      const transporter = nodemailer.createTransport({
        host: config.mail_host,
        port: config.mail_port || 587,
        secure: config.mail_port === 465, // true for 465, false for other ports
        auth: {
          user: config.mail_username,
          pass: config.mail_password,
        }
      });

      const mailOptions = {
        from: `"${config.mail_from_name || config.company_name}" <${config.mail_from_address || config.mail_username}>`,
        to: to,
        subject: subject,
        html: html
      };

      const info = await transporter.sendMail(mailOptions);
      console.log('Email sent: ' + info.response);
      return { success: true, message: 'Email sent successfully.' };

    } catch (error) {
      console.error('Error sending email:', error);
      return { success: false, message: 'Failed to send email.', error: error.message };
    }
  }

  /**
   * Send an SMS using the SMS API URL from the database
   * @param {string} number 
   * @param {string} message 
   */
  async sendSms(number, message) {
    try {
      const config = await this.getCompanyConfig();

      if (!config.sms_api_url || !config.sms_api_key || !config.sms_sender_id) {
        console.warn('SMS configuration is missing or incomplete.');
        return { success: false, message: 'SMS configuration incomplete.' };
      }

      // Format number (strip non-digits, ensure starts with country code for BD as example)
      let formattedNumber = number.replace(/[^0-9]/g, '');
      if (formattedNumber.startsWith('01') && formattedNumber.length === 11) {
        formattedNumber = '88' + formattedNumber;
      }

      const response = await axios.get(config.sms_api_url, {
        params: {
          api_key: config.sms_api_key,
          type: 'text',
          senderid: config.sms_sender_id,
          number: formattedNumber,
          message: message
        }
      });

      console.log('SMS API Response:', response.data);
      
      // Basic check for success (Bulksmsbd uses 202 for success)
      const respData = response.data;
      if (
        respData === 202 || 
        respData === '202' || 
        (typeof respData === 'string' && respData.includes('202')) ||
        (respData && respData.response_code == 202) || 
        (respData && respData.success === true) ||
        (respData && respData.error_code == 202)
      ) {
        return { success: true, message: 'SMS sent successfully.' };
      }

      return { success: false, message: `SMS gateway error. Code: ${respData}`, data: respData };

    } catch (error) {
      console.error('Error sending SMS:', error);
      return { success: false, message: 'Failed to send SMS via API.', error: error.message };
    }
  }
}

module.exports = new NotificationService();
