

const User = require('../models/userModel');
const Email = require('../models/email');
const fs = require('fs');
const pool = require('../config/db');
const userController = {
    addDeskOfficer: async (req, res, next) => {
        try {
            const { email, first_name, last_name, contacts } = req.body;
            const created_by = req.userId; 
            console.log(email)
            const userId = await User.create(
                email,
                first_name,
                last_name,
                contacts,
                created_by,
                 "DESK_OFFICER"
            );

            return res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Desk officer created successfully",
                data: { id: userId }
            });
        } catch (error) {
            next(error);
        }
    },

    createPartner: async (req, res, next) => {
        try {
            const { email, first_name, last_name, contacts, password } = req.body;
            const userId = await User.createPartner(
                email,
                first_name,
                last_name,
                contacts,
                password,
                "PARTNER_NOT_APPROVED"
            );

            return res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Partner Created",
                data: { id: userId }
            });
        } catch (error) {
            next(error);
        }
    },

    // Edit Desk Officer
    editDeskOfficer: async (req, res, next) => {
        try {
            const {user_id, first_name, last_name, contacts } = req.body;

            const affectedRows = await User.updateDeskOfficer(user_id, {
                first_name,
                last_name,
                contacts
            });

            if (affectedRows === 0) {
                return res.status(404).json({
                    success: false,
                    statusCode: 404,
                    message: "Desk officer not found or not updated"
                });
            }

            return res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Desk officer updated successfully"
            });
        } catch (error) {
            next(error);
        }
    },

    // Edit Desk Officer
    approvePartner: async (req, res, next) => {
        try {
            const {user_id} = req.body;

            console.log(user_id)
            const affectedRows = await User.approvePartner(user_id);

            if (affectedRows === 0) {
                return res.status(404).json({
                    success: false,
                    statusCode: 404,
                    message: "Partner Not Found"
                });
            }

            return res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Partner Approved"
            });
        } catch (error) {
            next(error);
        }
    },

    // Edit Desk Officer
    declinePartner: async (req, res, next) => {
        try {
            const {user_id} = req.body;

            const affectedRows = await User.declinePartner(user_id);

            if (affectedRows === 0) {
                return res.status(404).json({
                    success: false,
                    statusCode: 404,
                    message: "Partner Not Found"
                });
            }

            return res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Partner Declined"
            });
        } catch (error) {
            next(error);
        }
    },

    // Remove Desk Officer
    removeDeskOfficer: async (req, res, next) => {
        try {
            const {userId} = req.body;

            const affectedRows = await User.deleteDeskOfficer(userId);

            if (affectedRows === 0) {
                return res.status(404).json({
                    success: false,
                    statusCode: 404,
                    message: "Desk officer not found or not deleted"
                });
            }

            return res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Desk officer deleted successfully"
            });
        } catch (error) {
            next(error);
        }
    },

    // Get Desk Officers (already implemented)
    getDeskOfficers: async (req, res, next) => {
        try {

            const userId = req.userId

            const users = await User.getAll("DESK_OFFICER", userId);

            return res.status(200).json({

                success: true,
                statusCode: 200,
                message: "Success",
                data: users

            });

        } catch (error) {
            next(error);
        }
    },

    getPartners: async (req, res, next) => {
        try {
            const userId = req.userId;
            const users1 = await User.getAll("PARTNER", userId);
            const users2 = await User.getAll("PARTNER_DECLINED", userId);
            const users3 = await User.getAll("PARTNER_NOT_APPROVED", userId);
            
            // Combine all users into a single array
            const users = [...users1, ...users2, ...users3];

            return res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Success",
                data: users
            });
        } catch (error) {
            next(error);
        }
    },


    getCategorizedUsers: async (req, res, next) => {
    try {
        const result = await User.getCategorizedUsers(req.userId);
        
        return res.status(200).json({
            success: true,
            statusCode: 200,
            message: "Success",
            data: result
        });
    } catch (error) {
        next(error);
    }
},

    // MEMBER functions (exact same implementations but with "MEMBER" role)
    addMember: async (req, res, next) => {
        try {
            const { email, first_name, last_name, contacts } = req.body;
            const created_by = req.userId; 
            console.log(created_by)
            const userId = await User.create(
                email,
                first_name,
                last_name,
                contacts,
                created_by,
                 "MEMBER"
            );

            return res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Member created successfully",
                data: { id: userId }
            });
        } catch (error) {
            next(error);
        }
    },

    // Edit Member
    editMember: async (req, res, next) => {
        try {
            const {user_id, first_name, last_name, contacts } = req.body;
            
            const affectedRows = await User.updateDeskOfficer(user_id, {
                first_name,
                last_name,
                contacts
            });

            if (affectedRows === 0) {
                return res.status(404).json({
                    success: false,
                    statusCode: 404,
                    message: "Member not found or not updated"
                });
            }

            return res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Member updated successfully"
            });
        } catch (error) {
            next(error);
        }
    },

    // Remove Member
    removeMember: async (req, res, next) => {
        try {
            const {userId} = req.body;
            const affectedRows = await User.deleteMember(userId);

            if (affectedRows === 0) {
                return res.status(404).json({
                    success: false,
                    statusCode: 404,
                    message: "Member not found or not deleted"
                });
            }

            return res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Member deleted successfully"
            });
        } catch (error) {
            next(error);
        }
    },

    // Get Members
    getMembers: async (req, res, next) => {
        try {
            const userId = req.userId
            const users = await User.getMembers(userId);
            
            return res.status(200).json({
                success: true,
                statusCode: 200,
                message: "Success",
                data: users
            });
        } catch (error) {
            next(error);
        }
    },
    

    // Add to userController.js
sendOTP: async (req, res, next) => {
    try {
        const { email } = req.body;
        const user = await User.findByEmail(email);
        
        if (!user) {
            return res.status(404).json({
                success: false,
                statusCode: 404,
                message: "User with this email doesn't exist"
            });
        }
        
        // Generate and save OTP
        const { otp } = await User.generateResetToken(email);
        
        // Mock email sending function
        await Email.sendOTPEmail(email, otp);
        
        return res.status(200).json({
            success: true,
            statusCode: 200,
            message: "OTP sent to your email"
        });
    } catch (error) {
        next(error);
    }
},

verifyOTP: async (req, res, next) => {
    try {
        const { email, otp } = req.body;
        
        const token = await User.verifyOTP(email, otp);
        
        if (!token) {
            return res.status(400).json({
                success: false,
                statusCode: 400,
                message: "Invalid or expired OTP"
            });
        }
        
        return res.status(200).json({
            success: true,
            statusCode: 200,
            message: "OTP verified",
            data: { token }
        });
    } catch (error) {
        next(error);
    }
},

changePassword: async (req, res, next) => {
    try {
        const { token, newPassword, confirmPassword } = req.body;
        
        if (newPassword !== confirmPassword) {
            return res.status(400).json({
                success: false,
                statusCode: 400,
                message: "Passwords don't match"
            });
        }
        
        const success = await User.resetPassword(token, newPassword);
        
        if (!success) {
            return res.status(400).json({
                success: false,
                statusCode: 400,
                message: "Invalid or expired token"
            });
        }
        
        return res.status(200).json({
            success: true,
            statusCode: 200,
            message: "Password changed successfully"
        });
    } catch (error) {
        next(error);
    }
},


uploadProfile: async (req, res, next) => {
    try {
        if (!req.file) {
            return res.status(400).json({
                success: false,
                statusCode: 400,
                message: "No file uploaded"
            });
        }

        const userId = req.userId;
        const profileUrl = `/uploads/${req.file.filename}`;

        // Update user's profile URL in database
        const [result] = await pool.query(
            'UPDATE users SET profile_url = ? WHERE id = ?',
            [profileUrl, userId]
        );

        if (result.affectedRows === 0) {
            return res.status(404).json({
                success: false,
                statusCode: 404,
                message: "User not found"
            });
        }

        return res.status(200).json({
            success: true,
            statusCode: 200,
            message: "Profile picture uploaded successfully",
            data: { profileUrl }
        });
    } catch (error) {
        // Delete the uploaded file if error occurs
        if (req.file && fs.existsSync(req.file.path)) {
            fs.unlinkSync(req.file.path);
        }
        next(error);
    }
}
};

module.exports = userController;