import User from "../models/User.js"
import bcrypt from "bcryptjs"
import jwt from "jsonwebtoken"
import config from "../config.js"

const login = async (req, res) => {
    const { email, password } = req.body //구조분해해서 하나씩
    console.log( email, password)
    try { 
        const user = await User.findOne({email}).select('+password')
        if (!user) {
            return res.status(404).send(`${email}이 없습니다`)
        }
        const passwordMatch = await bcrypt.compare(password, user.password)
        if (passwordMatch) { 
            const token = jwt.sign({userId: user._id}, config.jwtSecret,{
                expiresIn: '7d'
            })
            res.cookie('token', token, {
                maxAge: config.cookieMaxAge,
                httpOnly: true,
                secure: config.env === 'production'
            })
            res.json({userId: user._id})
        } else {
            res.status(401).send('비밀번호가 일치하지 않습니다')
        }
        
    } catch (error) {
        console.log(error)
        res.status(500).send('로그인 에러')
    }
}

const logout = (req, res) => {
    res.clearCookie('token')
    res.send('Logout Successful')
}

export default { login, logout}