import { generateToken, verifyToken } from "../auth/auth.js"
import { connection } from "../configs/db.js"
import bcrypt from "bcryptjs"
import express from "express"

const authRoute = express.Router()


// Register route

authRoute.post("/register", async (req, res) => {
    try {
        const { username, email, password } = req.body
        if (!username || !email || !password) return res.status(400).json({ message: "Please provide all the required fields" })
        const [user] = await connection.query("SELECT * FROM users WHERE username = ? OR email = ?", [username, email])
        if(user.length > 0) return res.status(400).json({ message: "User already exists" })
        const hashedPassword = await bcrypt.hash(password, 10)
        const sql = `INSERT INTO users(username, email, password) VALUES(?, ?, ?)`
        const [result] = await connection.query(sql, [username, email, hashedPassword])
        if(result.affectedRows == 1) return res.status(201).json({ message: "User created successfully" })
        return res.status(500).json({ message: "Internal server error" })
    } catch (error) {
        console.log(error)
        return res.status(500).json({ message: "Internal server error" })
    }
})


// login route

authRoute.post("/login", async (req, res) => {
    try {
        const { username, password } = req.body
        if (!username || !password) return res.status(400).json({ message: "Please provide all the required fields" })
        const [user] = await connection.query("SELECT * FROM users WHERE username = ? OR email = ?", [username, username])
        if(!user) return res.status(401).json({ message: "Invalid username or password" })
        const isPasswordCorrect = await bcrypt.compare(password, user[0].password)
        if(!isPasswordCorrect) return res.status(401).json({ message: "Invalid username or password" })
        await generateToken(user[0], res)
        return res.status(200).json({ message: "Login successful" })
    } catch (error) {
        console.log(error)
        return res.status(500).json({ message: "Internal server error" })
    }
})

// logout route

authRoute.get("/logout", (req, res) => {
    try {
        res.clearCookie("token")
        return res.status(200).json({ message: "Logout successful" })
    } catch (error) {
        console.log(error)
        return res.status(500).json({ message: "Internal server error" })
    }
})


// check auth route

authRoute.get("/check", verifyToken, (req, res) => {
    try {
        const { role, username, id } = req.user

        return res.status(200).json({ role, username, id })
    } catch (error) {
        console.log(error)
        return res.status(500).json({ message: "Internal server error" })
    }
})

export default authRoute