const db = require('../utils/db.js')
const axios = require('axios')

// import controller function

const update_att_sms = async(req, res, next)=>{
    const id = 1;
    const {att_sms} = req.body;
    const sql = `UPDATE sms SET att_sms = ? WHERE id = ?`;
    try {
        db.query(sql, [att_sms, id], (err,result)=>{
            if(err) return res.status(400).json({message:err})
            res.status(200).json({message:'updated notify message!'})
        })
    } catch (error) {
        next(error)
    }
}

const update_apikey = async(req, res, next)=>{
    const id = 1;
    const {apikey} = req.body;
    const sql = `UPDATE sms SET api_key = ? WHERE id = ?`;
    try {
        db.query(sql, [apikey, id], (err,result)=>{
            if(err) return res.status(400).json({message:err})
            res.status(200).json({message:'updated api key!'})
        })
    } catch (error) {
        next(error)
    }
}

const blank_sms = async (req, res, next) => {
    const { phone, message } = req.body;
    const id = 1;
    const sql = `SELECT api_key FROM sms WHERE id = ?`;

    try {
        db.query(sql, [id], async (err, result) => {
            if (err) return res.status(400).json({ message: err });

            const api_key = result[0]?.api_key;
            const greenwebsms = new URLSearchParams();
            greenwebsms.append('token', api_key);
            greenwebsms.append('to', phone);
            greenwebsms.append('message', message);

            try {
                const response = await axios.post('https://api.bdbulksms.net/api.php', greenwebsms);
                if (response?.status == 200) {
                    return res.status(200).json({ message: `Sms sent successfully to: ${phone}` });
                } else {
                    return res.status(400).json({ message: `Failed to send SMS to: ${phone}` });
                }
            } catch (axiosError) {
                return res.status(500).json({ message: 'Error while sending SMS', error: axiosError.message });
            }
        });
    } catch (error) {
        next(error);
    }
}

const group_sms = async (req, res, next) => {
    const { classn, department, message } = req.body;
    const id = 1;

    const sql = `SELECT api_key FROM sms WHERE id = ?`;
    const sql2 = `SELECT * FROM students WHERE class = ? AND department = ?`;

    try {
        db.query(sql, [id], (err, result) => {
            if (err) return res.status(400).json({ message: err });

            const api_key = result[0]?.api_key;

            db.query(sql2, [classn, department], async (err2, result2) => {
                if (err2) return res.status(400).json({ message: `Student fetching error: ${err2}` });
                if (result2?.length === 0) return res.status(400).json({ message: 'Student records are empty!' });

                const smsPromises = result2.map((v) => {
                    const phone = v?.gnumber;
                    const greenwebsms = new URLSearchParams();
                    greenwebsms.append('token', api_key);
                    greenwebsms.append('to', phone);
                    greenwebsms.append('message', message);

                    return axios.post('https://api.bdbulksms.net/api.php', greenwebsms)
                        .then(response => response.status === 200)
                        .catch(() => false); // Treat errors as failed sends
                });

                try {
                    const results = await Promise.all(smsPromises);
                    const countmessage = results.filter(success => success).length;
                    return res.status(200).json({
                        message: `Group SMS sent successfully. Sent to ${countmessage} numbers.`
                    });
                } catch (sendError) {
                    return res.status(500).json({ message: 'Error while sending group SMS', error: sendError.message });
                }
            });
        });
    } catch (error) {
        next(error);
    }
};


const annoucement_sms = async (req, res, next) => {
    const { type, message } = req.body;
    const allowedTypes = ['students', 'teachers', 'instructors', 'committee']; // etc
    if (!allowedTypes.includes(type)) {
        return res.status(400).json({ message: 'Invalid type provided.' });
    }

    const id = 1;
    const sql = `SELECT api_key FROM sms WHERE id = ?`;
    const sql2 = `SELECT * FROM ${type}`;

    try {
        db.query(sql, [id], (err, result) => {
            if (err) return res.status(400).json({ message: err });

            const api_key = result[0]?.api_key;

            db.query(sql2, async (err2, result2) => {
                if (err2) return res.status(400).json({ message: `Fetching ${type} failed: ${err2}` });
                if (!result2?.length) return res.status(400).json({ message: 'No records found!' });

                // Prepare all SMS promises
                const smsPromises = result2.map((v) => {
                    const phone = type === 'students' ? v?.gnumber :
                                  type === 'teachers' ? v?.contactno : v?.phone;

                    const greenwebsms = new URLSearchParams();
                    greenwebsms.append('token', api_key);
                    greenwebsms.append('to', phone);
                    greenwebsms.append('message', message);

                    return axios.post('https://api.bdbulksms.net/api.php', greenwebsms)
                        .then(response => response.status === 200)
                        .catch(() => false); // Treat failed requests as false
                });

                try {
                    const results = await Promise.all(smsPromises);
                    const countmessage = results.filter(success => success).length;
                    return res.status(200).json({
                        message: `Announcement SMS sent to ${countmessage} recipients.`
                    });
                } catch (axiosError) {
                    return res.status(500).json({ message: 'Error while sending announcement SMS', error: axiosError.message });
                }
            });
        });
    } catch (error) {
        next(error);
    }
};


module.exports = {update_att_sms, update_apikey, blank_sms, group_sms, annoucement_sms}