const bcrypt = require("bcrypt")
const User = require("../models/users.m")
const jwt = require("jsonwebtoken")

exports.registerUser = async (req, res) => {
    try {
        const { names, email, password, role } = req.body;
        if (!names || !email || !password) return res.status(400).json({ message: "All fields are required" })
        const existsUser = await User.findOne({ email })

        if (existsUser) return res.status(403).json("User alreay exists")

        const hashedPassword = await bcrypt.hash(password, 10)

        const newUser = new User({
            names,
            email,
            password: hashedPassword,
            role
        })

        await newUser.save()

        res.status(201).json({
            message: "User created Successfully",
            user: newUser
        })

    } catch (error) {
        return res.status(500).json({ message: "Internal Server Error", error: error.message })
    }
}

exports.loginUser = async (req, res) => {
    try {
        const { email, password } = req.body;
        if (!email || !password) return res.status(400).json({ message: "All fields are required" })

        const userExists = await User.findOne({ email })
        if (!userExists) return res.status(404).json({ message: "USER NOT FOUND, Register first" })

        const isMatch = await bcrypt.compare(password, userExists.password)
        if (!isMatch) return res.status(403).json({ message: "Enter the true password" })

        const token = jwt.sign(
            { id: userExists._id, role: userExists.role },
            process.env.JWT_SECRET,
            { expiresIn: "30d" }
        )

        res.status(200).json({
            message: "Logged In Well",
            data: {
                userExists,
                token: token
            }
        })
    } catch (error) {
        return res.status(500).json({
            message: "Internal Server Error", error: error.message})
    }
}