const Admin = require('../models/Admin')
// const Creation = require('../models/Creation')
// const User = require('../models/User')
// const Game = require('../models/Game')

const { Op, fn, col } = require('sequelize');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const axios = require('axios');
const date = require('date-and-time');
const db = require('../config/db.config');
const moment = require('moment-timezone');

require('dotenv').config()

exports.cashiersAll = async (req, res) => {
    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }
        Admin.findAll({
            attributes: { exclude: ['password', 'created_at', 'updated_at'] }
        })
            .then(admins => {
                res.status(200).json(admins);
            })
            .catch(err => {
                res.status(500).json({ error: err.message });
            });
    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
};

exports.cashiers = async (req, res) => {
    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }
        Admin.findAll({
            where: {
                role: { [Op.ne]: 'Super' } // Assuming the column name is 'role'
            },
            attributes: { exclude: ['password', 'created_at', 'updated_at'] }
        })
            .then(admins => {
                res.status(200).json(admins);
            })
            .catch(err => {
                res.status(500).json({ error: err.message });
            });
    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
};

exports.loggedInCashier = async (req, res) => {
    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }
        Admin.findAll({
            where: {
                role: { [Op.ne]: 'Super' },
                is_loggedin: 1
            },
            attributes: { exclude: ['password', 'created_at', 'updated_at'] }
        })
            .then(admins => {
                res.status(200).json(admins);
            })
            .catch(err => {
                res.status(500).json({ error: err.message });
            });
    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
};
exports.logoutCashier = async (req, res) => {
    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }
        if ( admin.role != 'Super') {
            return res.status(401).json({ error: 'Unauthorized' });
        }
        const { admin_id } = req.body;

        if (!admin_id ) {
            return res.status(400).json({ error: 'Admin ID  is required' });
        }

        const cashier = await Admin.findOne({ where: { id: admin_id } });
        if (!cashier) {
            return res.status(404).json({ error: 'Admin Not Found!' });
        }

        cashier.is_loggedin = '0';
        await cashier.save();
      
        return res.status(200).json({ message: 'Cashier logged out' });

    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
}
exports.permissions = async (req, res) => {
    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }
        Admin.findAll({
            where: {
                role: { [Op.ne]: 'Super' } // Assuming the column name is 'role'
            },
            attributes: {
                exclude: ['email', 'phone', 'password', 'role', 'remember_token', 'is_loggedin', 'ban',
                    'otp', 'reason', 'first_login', 'pref', 'created_at', 'updated_at', 'latest_activity', 'retry_count']
            }
        })
            .then(admins => {
                res.status(200).json(admins);
            })
            .catch(err => {
                res.status(500).json({ error: err.message });
            });
    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
};
exports.updatePermission = async (req, res) => {
    const { admin_id, p_status, p_name } = req.body;

    if (!admin_id || p_status === undefined || !p_name) {
        return res.status(401).json({ error: 'Admin ID / Permission Status / Permission Name is missing' });
    }

    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }

        const permissionAdmin = await Admin.findOne({ where: { id: admin_id } });
        if (!permissionAdmin) {
            return res.status(404).json({ error: 'Permission Admin not found' });
        }

        // Update the specific permission
        switch (p_name.toLowerCase()) {
            case 'user':
                permissionAdmin.user = p_status;
                break;
            case 'creation':
                permissionAdmin.creation = p_status;
                break;
            case 'deposit':
                permissionAdmin.deposit = p_status;
                break;
            case 'redeem':
                permissionAdmin.redeem = p_status;
                break;
            case 'games':
                permissionAdmin.games = p_status;
                break;
            case 'userip':
                permissionAdmin.userip = p_status;
                break;
            case 'addnote':
                permissionAdmin.addnote = p_status;
                break;
            case 'verify':
                permissionAdmin.verify = p_status;
                break;
            case 'userpaymentmethods':
                permissionAdmin.userpaymentmethods = p_status;
                break;
            case 'userwheel':
                permissionAdmin.userwheel = p_status;
                break;
            case 'usergifting':
                permissionAdmin.usergifting = p_status;
                break;
            case 'usermodify':
                permissionAdmin.usermodify = p_status;
                break;
            case 'userskipmob':
                permissionAdmin.userskipmob = p_status;
                break;
            case 'useractivities':
                permissionAdmin.useractivities = p_status;
                break;
            case 'userdelete':
                permissionAdmin.userdelete = p_status;
                break;
            case 'usertotals':
                permissionAdmin.usertotals = p_status;
                break;
            case 'useremails':
                permissionAdmin.useremails = p_status;
                break;
            case 'withdraw':
                permissionAdmin.withdraw = p_status;
                break;
            case 'ach':
                permissionAdmin.ach = p_status;
                break;
            case 'bonus':
                permissionAdmin.bonus = p_status;
                break;
            case 'raffles':
                permissionAdmin.raffles = p_status;
                break;
            case 'paymentmethods':
                permissionAdmin.paymentmethods = p_status;
                break;
            case 'paymentmethodsupdate':
                permissionAdmin.paymentmethodsupdate = p_status;
                break;
            case 'payoutmethods':
                permissionAdmin.payoutmethods = p_status;
                break;
            case 'payoutmethodsupdate':
                permissionAdmin.payoutmethodsupdate = p_status;
                break;
            case 'flaggedpayments':
                permissionAdmin.flaggedpayments = p_status;
                break;
            case 'avsban':
                permissionAdmin.avsban = p_status;
                break;
            case 'codb':
                permissionAdmin.codb = p_status;
                break;
            case 'fraudusers':
                permissionAdmin.fraudusers = p_status;
                break;
            case 'wheelspins':
                permissionAdmin.wheelspins = p_status;
                break;
            case 'giftcards':
                permissionAdmin.giftcards = p_status;
                break;
            case 'refferals':
                permissionAdmin.refferals = p_status;
                break;
            case 'blockedbins':
                permissionAdmin.blockedbins = p_status;
                break;
            case 'uips':
                permissionAdmin.uips = p_status;
                break;
            case 'gamelinks':
                permissionAdmin.gamelinks = p_status;
                break;
            case 'searchtxn':
                permissionAdmin.searchtxn = p_status;
                break;
            case 'createcashier':
                permissionAdmin.createcashier = p_status;
                break;
            case 'cashierban':
                permissionAdmin.cashierban = p_status;
                break;
            case 'cashierdelete':
                permissionAdmin.cashierdelete = p_status;
                break;
            case 'cashiercreations':
                permissionAdmin.cashiercreations = p_status;
                break;
            case 'cashiervers':
                permissionAdmin.cashiervers = p_status;
                break;
            case 'cashierpermissions':
                permissionAdmin.cashierpermissions = p_status;
                break;
            case 'cashierpassword':
                permissionAdmin.cashierpassword = p_status;
                break;
            case 'pass_resets':
                permissionAdmin.pass_resets = p_status;
                break;
            case 'pending_vers':
                permissionAdmin.pending_vers = p_status;
                break;
            case 'duplicate_users':
                permissionAdmin.duplicate_users = p_status;
                break;
            case 'bonus_codes':
                permissionAdmin.bonus_codes = p_status;
                break;
            case 'api_logs':
                permissionAdmin.api_logs = p_status;
                break;
            case 'email_logs':
                permissionAdmin.email_logs = p_status;
                break;
            case 'webhook_ip_logs':
                permissionAdmin.webhook_ip_logs = p_status;
                break;
            case 'game_charts':
                permissionAdmin.game_charts = p_status;
                break;
            case 'dep_with_charts':
                permissionAdmin.dep_with_charts = p_status;
                break;
            case 'contact_submits':
                permissionAdmin.contact_submits = p_status;
                break;
            case 'activity_logs':
                permissionAdmin.activity_logs = p_status;
                break;
            case 'dashboard_charts':
                permissionAdmin.dashboard_charts = p_status;
                break;
            case 'auto_pilot_deposit':
                permissionAdmin.auto_pilot_deposit = p_status;
                break;
            case 'auto_pilot_redeem':
                permissionAdmin.auto_pilot_redeem = p_status;
                break;
            case 'auto_pilot_resets':
                permissionAdmin.auto_pilot_resets = p_status;
                break;
            case 'bonuses':
                permissionAdmin.bonuses = p_status;
                break;
            case 'endis_bonus':
                permissionAdmin.endis_bonus = p_status;
                break;
            case 'bonususers':
                permissionAdmin.bonususers = p_status;
                break;
            case 'bonusdashboard':
                permissionAdmin.bonusdashboard = p_status;
                break;
            case 'reported_withdraw':
                permissionAdmin.reported_withdraw = p_status;
                break;
            case 'reported_deposit':
                permissionAdmin.reported_deposit = p_status;
                break;
            default:
                return res.status(400).json({ error: 'Invalid permission name' });
        }

        await permissionAdmin.save();

        return res.status(200).json({ message: 'Permission updated successfully' });

    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
}
exports.createCashier = async (req, res) => {
    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }
        const { firstName, lastName, username, email, phone } = req.body;

        if (!firstName || !username || !email || !phone) {
            return res.status(400).json({ error: 'First Name, Username, Email, and Phone are required' });
        }

        const existingCashier = await Admin.findOne({
            where: {
                [Op.or]: [
                    { username: username },
                    { email: email }
                ]
            }
        });

        if (existingCashier) {
            return res.status(409).json({ error: 'Username or Email already exists' });
        }
        const passx = generateRandomString();
        const hashedPassword = await bcrypt.hashSync(passx);

        const cashier = await Admin.create({
            username: username,
            password: hashedPassword,
            first: firstName,
            last: lastName || '',
            email: email,
            phone: phone,
            role: 'Admin',
            pref: 'magiclink'
        });
        sendEmail(email, username, passx);
        return res.status(201).json({ message: 'Cashier created successfully', cashier });

    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
}
exports.updateCashier = async (req, res) => {
    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }
        const { firstName, lastName, username, email, phone, admin_id } = req.body;

        if (!firstName || !username || !email || !phone || !admin_id) {
            return res.status(400).json({ error: 'Admin ID, First Name, Username, Email, and Phone are required' });
        }


        const cashier = await Admin.findOne({ where: { id: admin_id } });
        if (!cashier) {
            return res.status(404).json({ error: 'Admin Not Found!' });
        }
        cashier.username = username;
        cashier.first = firstName;
        cashier.last = lastName;
        cashier.email = email;
        cashier.phone = phone;
        await cashier.save();

        return res.status(200).json({ message: 'Cashier updated successfully' });

    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
}
exports.banCashier = async (req, res) => {
    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }
        const { admin_id } = req.body;

        if (!admin_id) {
            return res.status(400).json({ error: 'Admin ID is required' });
        }


        const cashier = await Admin.findOne({ where: { id: admin_id } });
        if (!cashier) {
            return res.status(404).json({ error: 'Admin Not Found!' });
        }
        cashier.ban = '1';
        await cashier.save();

        return res.status(200).json({ message: 'Cashier banned successfully' });

    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
}
exports.unbanCashier = async (req, res) => {
    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }
        const { admin_id } = req.body;

        if (!admin_id) {
            return res.status(400).json({ error: 'Admin ID is required' });
        }


        const cashier = await Admin.findOne({ where: { id: admin_id } });
        if (!cashier) {
            return res.status(404).json({ error: 'Admin Not Found!' });
        }
        cashier.ban = '0';
        await cashier.save();

        return res.status(200).json({ message: 'Cashier un-banned successfully' });

    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
}
exports.deleteCashier = async (req, res) => {
    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }
        const { admin_id } = req.body;

        if (!admin_id) {
            return res.status(400).json({ error: 'Admin ID is required' });
        }


        const cashier = await Admin.findOne({ where: { id: admin_id } });
        if (!cashier) {
            return res.status(404).json({ error: 'Admin Not Found!' });
        }

        await cashier.destroy();

        return res.status(200).json({ message: 'Cashier removed successfully' });

    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
}

exports.updateProfile = async (req, res) => {
    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }
        const { email, phone, pref } = req.body;

        if (!email && !phone && !pref) {
            return res.status(400).json({ error: 'At least one field (email, phone, pref) is required' });
        }

        const cashier = await Admin.findOne({ where: { id: admin.id } });
        if (!cashier) {
            return res.status(404).json({ error: 'Admin Not Found!' });
        }

        // Update only the fields that are present in the request
        if (email) cashier.email = email;
        if (phone) cashier.phone = phone;
        if (pref) cashier.pref = pref;

        await cashier.save();

        return res.status(200).json({ status: 'success', message: 'Cashier updated successfully' });
    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
}

exports.updatePassword = async (req, res) => {
    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }
        if (admin.cashierpassword == '0' && admin.role != 'Super') {
            return res.status(401).json({ error: 'Unauthorized' });
        }
        const { admin_id, password } = req.body;

        if (!admin_id || !password) {
            return res.status(400).json({ error: 'Admin ID / Password is required' });
        }

        const cashier = await Admin.findOne({ where: { id: admin_id } });
        if (!cashier) {
            return res.status(404).json({ error: 'Admin Not Found!' });
        }

        const hashedPassword = await bcrypt.hashSync(password);
        cashier.password = hashedPassword;
        await cashier.save();
        sendEmail(cashier.email, cashier.username, password);
        return res.status(200).json({ message: 'Cashier password updated successfully' });

    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
}

exports.updateOTP = async (req, res) => {
    try {
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!authHeader) {
            return res.status(401).json({ error: 'Authorization header is missing' });
        }

        const token = authHeader.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: 'Token is missing' });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const adminId = decoded.id;

        const admin = await Admin.findOne({ where: { id: adminId } });
        if (!admin) {
            return res.status(404).json({ error: 'Admin not found' });
        }
        // if ( admin.role != 'Super') {
        //     return res.status(401).json({ error: 'Unauthorized' });
        // }
        const { admin_id, otps } = req.body;

        if (!admin_id || !otps) {
            return res.status(400).json({ error: 'Admin ID / OTPs is required' });
        }

        const cashier = await Admin.findOne({ where: { id: admin_id } });
        if (!cashier) {
            return res.status(404).json({ error: 'Admin Not Found!' });
        }
        cashier.otp_allow = otps;
        await cashier.save();
        return res.json({ status: 'success', message: 'OTP Allowance Updated!' })

    } catch (error) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token is invalid or has expired' });
        }

        console.error(error);
        res.status(500).json({ error: 'Internal server error' });
    }
}
function generateRandomString(length = 8) {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
}
async function sendEmail(email, username, passx) {
    const payload = {
        subject: 'Account Credentials',
        email: email,
        name: username,
        mail: `
            <!DOCTYPE html>
            <html lang="en" dir="ltr" xmlns:v="urn:schemas-microsoft-com:vml">
            <head>
                <meta charset="utf-8">
                <meta name="x-apple-disable-message-reformatting">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <meta name="format-detection" content="telephone=no, date=no, address=no, email=no, url=no">
                <title>Account Credentials</title>
                <style>
                    /* Add your CSS styles here */
                    .hover-bg-brand-600:hover {
                        background-color: #0047C3 !important;
                    }

                    .hover-text-brand-700:hover {
                        color: #003CA5 !important;
                    }

                    .hover-text-decoration-underline:hover {
                        text-decoration: underline !important;
                    }

                    @media (max-width: 640px) {
                        .sm-mt-4 {
                            margin-top: 16px !important;
                        }

                        .sm-block {
                            display: block !important;
                        }

                        .sm-w-full {
                            width: 100% !important;
                        }

                        .sm-px-4 {
                            padding-left: 16px !important;
                            padding-right: 16px !important;
                        }

                        .sm-py-6 {
                            padding-top: 24px !important;
                            padding-bottom: 24px !important;
                        }
                    }
                </style>
            </head>
            <body style="margin: 0; width: 100%; background-color: #fff; padding: 0; -webkit-font-smoothing: antialiased; word-break: break-word">
                <div style="display: none">Bonus Granted!</div>
                <div role="article" aria-roledescription="email" aria-label="Please confirm your email address" lang="en">
                    <table style="width: 100%; font-family: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif" cellpadding="0" cellspacing="0" role="none">
                        <tr>
                            <td align="center" style="background-color: #fff;">
                                <table class="sm-w-full" style="width: 1366px" cellpadding="0" cellspacing="0" role="none">
                                    <tr>
                                        <td class="sm-px-4 sm-py-6" style="background-color: #fff; padding: 48px 40px; text-align: center">
                                            <div style="margin-bottom: 24px">
                                                <a href="https://wallet.sweepstake.mobi" style="text-decoration: none; color: #0047C3">
                                                    <p>SweepStake Mobi</p>
                                                </a>
                                            </div>
                                            <p style="margin: 0; font-size: 21px; line-height: 28px; color: #4A5566">Hi ${username},</p>
                                            <p style="margin: 0; font-size: 21px; line-height: 28px; color: #4A5566">Your password for login is: ${passx}</p>
                                            <div role="separator" style="line-height: 16px">&zwj;</div>
                                            <div style="text-align: center;">
                                                <div role="separator" style="background-color: #E1E1EA; height: 1px; line-height: 1px; margin: 64px 0 16px">&zwj;</div>
                                                <p style="margin: 0 0 16px; font-size: 12px; line-height: 16px; color: #8492A6">
                                                    This email was sent to you as a registered member of
                                                    <a href="https://sweepstake.mobi" class="hover-text-brand-700 hover-text-decoration-underline" style="text-decoration: none; color: #0047C3; display: inline-block;">SweepStake Mobi</a>. 
                                                    Use of the service and website is subject to our 
                                                    <a href="https://sweepstake.mobi/tnc.php" class="hover-text-brand-700 hover-text-decoration-underline" style="text-decoration: none; color: #0047C3; display: inline-block;">Terms of Use</a>
                                                    and
                                                    <a href="https://sweepstake.mobi/privacy-policy.php" class="hover-text-brand-700 hover-text-decoration-underline" style="text-decoration: none; color: #0047C3; display: inline-block;">Privacy Statement</a>.
                                                </p>
                                                <p style="margin: 0; font-size: 12px; line-height: 16px; color: #8492A6;">&copy; 2024 SweepStake Mobi. All rights reserved.</p>
                                            </div>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </div>
            </body>
            </html>
        `
    };

    try {
        const response = await axios.post(
            'https://swback.logiclane.tech/api/email',
            payload,
            {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer 4d0f394ec46be1c61d203a4df09da3277aa8c520d922533bf332c7db2c261f61'
                }
            }
        );

        return response.data;
    } catch (error) {
        console.error('Error sending email:', error);
        // throw new Error('Failed to send email');
        // return res.status(500).json({ error: 'Failed to send email' });
    }
}
