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

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: "all fields are required please"})
        }

        const doesExists = await User.findOne({ username })
        if(doesExists){
            return res.status(400).json({ message: "username arleady taken"})
        }
        const hashedPass = await bcrypt.hash(password, 10)
        const user = new User({ username, password: hashedPass })
        await user.save()
        return res.status(201).json({ message: "new user created successfully "})
    }catch(error){
        console.log(error)
        return res.status(500).json({ message: "server error"})
    }
})

//login

authRouter.post("/login", async(req, res ) => {
    try{
        const { username, password } = req.body
        if(!username || !password){
            return res.status(400).json({ message: "all fields are required please"})
        }
        const doesExists = await User.findOne({ username })
        if(!doesExists){
            return res.status(400).json({ message: "invalid username or password"})
        }
        const isPassCorrect = await bcrypt.compare(password, doesExists.password)
        if(!isPassCorrect){
            return res.status(400).json({ message: "invalid username or password"})
        }
        generateToken(doesExists, res)
        return res.status(200).json({ message: "login successful"})
    }catch(error){
        console.log(error)
        return res.status(500).json({ message: "server error"})
    }
})

//logout

authRouter.post("/logout", async(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: "server error"})
    }
})

// check auth

authRouter.get("/check", verifyToken, async(req, res) =>{
    try {
        const username = req.username
        const id = req.id
        return res.status(200).json({ username, id})
    } catch (error) {
        
    }
})

export default authRouter