import { generateToken, verifyToken } from "../auth/auth.js";
import User from "../models/User.model.js";
import express from "express";
import bcrypt from "bcryptjs";

const authRouter = express.Router();

// register

authRouter.post("/register", async(req, res) => {
    try {
        const { username, password } = req.body;
        if(!username || !password) {
            return res.status(400).json({ message: "Username and password are required" });
        }
        let role = "user"
        const user = await User.findOne({ username });
        
        if(user) {
            return res.status(400).json({ message: "User already exists" });
        }
        const hashedPassword = await bcrypt.hash(password, 10);
        const newUser = new User({ username, password: hashedPassword, role });

        await newUser.save();
        generateToken(newUser, res);

        return res.status(201).json({ message: "User created successfully", username: newUser.username });
    } catch (error) {
        console.error("Error registering user:", error);
        return res.status(500).json({ message: "Error registering user" });
    }
})

// promote to admin 

authRouter.post("/promote", verifyToken, async(req, res) => {
    try {
        if(req.user.role != "admin") {
            return res.status(401).json({ message: "You are not authorized to perform this action" });
        }
        const { username, code } = req.body;
        if(!username || !code) {
            return res.status(400).json({ message: "Username and code are required" });
        }
        const user = await User.findOne({ username });
        if(!user) {
            return res.status(404).json({ message: "User not found" });
        }
        const checkCode = (code === parseInt(process.env.PROMOTE_CODE));
        if(!checkCode) {
            return res.status(401).json({ message: "Invalid code" });
        }
        const promoteUser = await User.findOneAndUpdate({ username }, { role: "admin" }, { new: true });
        generateToken(promoteUser, res);
        return res.status(201).json({ message: "User promoted successfully" });
    } catch (error) {
        console.error("Error promoting user:", error);
        return res.status(500).json({ message: "Error promoting user" });
    }
})

// login

authRouter.post("/login", async(req, res) => {
    try {
        const { username, password } = req.body;
        if(!username || !password) {
            return res.status(400).json({ message: "Username and password are required" });
        }
        const user = await User.findOne({ username });
        if(!user) {
            return res.status(404).json({ message: "User not found" });
        }
        const isMatch = await bcrypt.compare(password, user.password);
        if(!isMatch) {
            return res.status(401).json({ message: "Invalid username or password" });
        }
        generateToken(user, res);
        return res.status(200).json({ message: "Login successful", username: user.username });
    } catch (error) {
        console.error("Error logging in:", error);
        return res.status(500).json({ message: "Error logging in" });
    }
})

// check if user is logged in

authRouter.get("/check", verifyToken, async(req, res) => {
    try {
        const id = req.user.id;
        const username = req.user.username;
        const role = req.user.role;
        return res.status(200).json({ id, username, role });
    } catch (error) {
        console.error("Error checking user:", error);
        return res.status(500).json({ message: "Error checking user" });
    }
})

//logout

authRouter.get("/logout", verifyToken, async(req, res) => {
    try {
        res.clearCookie("jwt");
        return res.status(200).json({ message: "Logged out successfully" });
    } catch (error) {
        console.error("Error logging out:", error);
        return res.status(500).json({ message: "Error logging out" });
    }
})

export default authRouter;