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

const authRouter = express.Router()

// 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 findUser = await User.findOne({ username })
        if(!findUser) {
            return res.status(404).json({ message: "user not found" })
        }

        const isPasswordMatch = await bcrypt.compare(password, findUser.password)
        if(!isPasswordMatch) {
            return res.status(401).json({ message: "invalid credentials" })
        }

        const token = await generateToken(findUser, res)
        return res.status(200).json({ message: "login successful", token })
    }
    catch (error) {
        console.error(error)
        return res.status(500).json({ message: "Internal server error" })
    }
})


// 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" })
        }

        const doesExists = await User.findOne({ username })
        if(doesExists){
            return res.status(400).json({ message: "username already exists" })
        }

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

// logout

authRouter.post("/logout", async(req, res) => {
    try{
        res.clearCookie("jwt")
        return res.status(200).json({ message: "logout successful" })
    }catch(error){
        console.log(error)
        return res.status(500).json({ message: "Internal server error" })
    }
})

//checkMe

authRouter.get("/check", verifyToken, async(req, res) => {
    try{
        let username = req.username
        let id = req.id
        return res.status(200).json({ username, id})
    }catch(error){
        console.log(error)
        return res.status(500).json({ message: "Internal server error" })
    }
})
export default authRouter