const dbConnect = require('../configs/dbConnection.js');
const {sendOtp, verifyOtp} = require('../../smsapi/model/smsModel.js');
const { deletionRequestFailureEmail } = require('../../emailapi/model/deletionAccountFailEmailModel');
const { accountDeletionRequestEmail } = require('../../emailapi/model/deletionEmailModel');

// exports.deleteAccount = async (req, res) => {
//     try{
//         const {mobile, email, otp, } = req.body;
//         console.log (mobile, email, otp);
        
//         const verifyOtpResponse = await verifyOtp(mobile, otp);
//         // console.log("verifyOtpResponse:", verifyOtpResponse.Details );
        
//         if (verifyOtpResponse.Details === "OTP Mismatch") {
//             return res.status(404). json({error: 'otp verfication failed'});
//         };

//         //chck if user exists in db
        
//         const [rows] =  await dbConnect.query(`SELECT * FROM ulogin WHERE uuser = ? AND umail= ?`,
//         [mobile, email]
//         );
        
//         console.log(rows);
        
//         // Check if rows[0] exists to avoid runtime error if user not found
//         if (!rows || rows.length === 0) {
//         const emailResult = await deletionRequestFailureEmail(email);
//         // console.log(emailResult);   
            
//         res.status(404).json({ error: "User not found."});;
//         }
        
        
        
//         const [deleteUser] = await dbConnect.query(`INSERT INTO accountdeletion (umob, umail, deletionid) VALUES (?, ?, ?)`,
//         [mobile, email, null] 
//         );
        
//         const deletionId = deleteUser.insertId
//         // console.log(deletionId);
        
//         const emailResult = await accountDeletionRequestEmail(email, deletionId);
//         console.log(emailResult);
    
//         if (!emailResult) {
//         return res.status(500).json({ error: 'Some error in sending account deletion email' });
//     }
    
//         return res.status(200).json({msg: 'deletion request registered'})
       
//         } catch (error) {
//         // console.error('Error:', error.message);
//         res.status(500).json({ error: error.message });
//   }
// };



exports.deleteAccount = async (req, res) => {
    try {
        const { mobile, email, otp } = req.body;

        if (!mobile || !email) {
            return res.status(400).json({ error: 'Mobile number and email are required' });
        }

        const trimmedMobile = mobile.trim();
        const trimmedEmail = email.trim();

        // -----------------------------
        // Step 1: Check if user exists
        // -----------------------------
        const [userRows] = await dbConnect.query(
            `SELECT * FROM ulogin WHERE uuser = ? AND umail = ?`,
            [trimmedMobile, trimmedEmail]
        );

        if (!userRows || userRows.length === 0) {
            await deletionRequestFailureEmail(trimmedEmail); // optional: send failure email
            return res.status(404).json({ error: 'User not found' });
        }

        // -----------------------------
        // Step 2: If OTP not provided → send OTP
        // -----------------------------
        if (!otp) {
            const formattedMobile = '+91' + trimmedMobile.replace(/\D/g, '').replace(/^0+|^91+/, '');
            const sendOtpResponse = await sendOtp(formattedMobile, "BOBROSOTP");
            return res.status(200).json({ msg: 'OTP sent', sendOtpResponse });
        }

        // -----------------------------
        // Step 3: If OTP provided → verify OTP
        // -----------------------------
        const verifyOtpResponse = await verifyOtp(trimmedMobile, otp);
        if (verifyOtpResponse.Details === "OTP Mismatch") {
            return res.status(400).json({ error: 'OTP verification failed' });
        }

        // -----------------------------
        // Step 4: Insert deletion request
        // -----------------------------
        const [deleteUser] = await dbConnect.query(
            `INSERT INTO accountdeletion (umob, umail, deletionid) VALUES (?, ?, ?)`,
            [trimmedMobile, trimmedEmail, null]
        );

        const deletionId = deleteUser.insertId;

        // -----------------------------
        // Step 5: Send deletion request email
        // -----------------------------
        const emailResult = await accountDeletionRequestEmail(trimmedEmail, deletionId);
        if (!emailResult) {
            return res.status(500).json({ error: 'Failed to send account deletion email' });
        }

        return res.status(200).json({ msg: 'Deletion request registered' });

    } catch (error) {
        console.error('Error:', error.message);
        res.status(500).json({ error: error.message });
    }
};
