

// for creating token for login
const jwt = require("jsonwebtoken");
const { User } = require("../models/userModel");

const authControllers = {
    signup: async (req, res) => {
        try {
            const { username, email, password, role, status } = req.body;
            // Validate required fields
            if (!username || !email || !password) {
                return res.status(400).json({ success: false, message: 'Please provide username, email and password' });
            }

            // Check if user with email already exists
            const existingEmail = await User.findByEmail(email);
            if (existingEmail) {
                return res.status(400).json({ success: false, message: 'Email already in use' });
            }

            // Check if username already exists
            const existingUsername = await User.findByUsername(username);
            if (existingUsername) {
                return res.status(400).json({ success: false, message: 'Username already taken' });
            }


            // Create new user
            const user = await User.create({ username, email, password, role, status });

            res.status(201).json({
                success: true,
                message: 'User registered successfully',
                data: {
                    id: user.id,
                    username: user.username,
                    email: user.email,
                    role: user.role,
                    status: user.status
                }
            });
        } catch (error) {
            console.error('Registration error:', error);
            res.status(500).json({ success: false, message: 'Error registering user' });
        }
    },

    login: async (req, res) => {
        try {
            const { email, password } = req.body;

            // Validate required fields
            if (!email || !password) {
                return res.status(400).json({ success: false, message: 'Please provide email and password' });
            }

            // Find user by email
            const user = await User.findByEmail(email);
            if (!user) {
                return res.status(401).json({ success: false, message: 'Invalid credentials' });
            }
            // Verify password
            const isPasswordValid = await User.verifyPassword(password, user.password);
            if (!isPasswordValid) {
                return res.status(401).json({ success: false, message: 'Invalid credentials' });
            }
            if (user.dataValues.status == 0) {
                return res.status(401).json({ success: false, message: 'You are not allowed to access If you need Connect to our Admin' });
            }

            // Generate JWT token
            const payload = { id: user.id, username: user.username, role: user.role }

            const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '24h' });

            res.status(200).json({
                success: true,
                message: 'Login successful',
                token,
                data: {
                    id: user.id,
                    username: user.username,
                    email: user.email,
                    role: user.role
                }
            });
        } catch (error) {
            console.error('Login error:', error);
            res.status(500).json({ success: false, message: 'Error during login' });
        }
    },


    deleteUser: async (req, res) => {
        const { id } = req.params
        const { role } = req.user
        try {
            const isDeleted = await User.deleteUser(id, role)
            if (isDeleted) {
                res.status(200).json({
                    success: true,
                    ...isDeleted
                });
            } else {
                return res.status(401).json({
                    success: false,
                    message: 'Not authorized to do this'
                });
            }
        } catch (error) {
            res.status(500).json({ success: false, message: 'Internal Server Error' });
        }


    },
    updateUser: async (req, res) => {
        const { id } = req.params
        const updatedData = req.body
        const { role } = req.user
        try {
            const isUpdate = await User.updateUser(id, updatedData, role)
            if (isUpdate) {
                res.status(200).json({
                    sucess: true,
                    message: "User Updated Successfully !"
                });
            } else {
                return res.status(401).json({
                    success: false,
                    message: 'Not authorized to do this'
                });
            }
        } catch (error) {
            res.status(500).json({ success: false, message: 'Internal Server Error' });

        }


    },
    getAllUsers: async (req, res) => {

        const { role } = req.user
        try {
            const users = await User.getUsers(role);
            if (users) {
                res.status(200).json({
                    sucess: true,
                    message: "User Fetch Successfully !",
                    data: users
                });
            } else {
                return res.status(401).json({
                    success: false,
                    message: 'Not authorized to do this'
                });
            }
        } catch (error) {
            res.status(500).json({ success: false, message: 'Internal Server Error' });

        }


    },




    // Get Single User
    getSingleUser: async (req, res) => {
        const { id } = req.params;
        try {
            const unit = await User.Get_Single_User(id);

            if (unit) {
                res.status(200).json({
                    success: true,
                    message: "User fetched successfully!",
                    data: unit,
                });
            } else {
                res.status(404).json({
                    success: false,
                    message: "User not found",
                });
            }
        } catch (error) {
            res.status(500).json({
                success: false,
                message: error.message,
            });
        }
    },
}
module.exports = authControllers
