const Router = require("express");
const User = require("../models/User");
const config = require("config")
const bcrypt = require("bcryptjs")
const jwt = require('jsonwebtoken')
const {check, validationResult} = require('express-validator')
const routers = new Router();
const authMiddleware = require('../middleware/auth')

routers.post(
    '/registration',
    [
        check('email', 'Некорректный email').isEmail(),
        check('password', 'Минимальная длина пароля 6 символов').isLength({ min: 6 })
    ],
    async (req,res)=>{
        try{
            const errors = validationResult(req)
            if (!errors.isEmpty()) {
              return res.status(400).json({
                errors: errors.array(),
                message: 'Некорректный данные при регистрации'
              })
            }
            const{email,password}= req.body
            const candidate = await User.findOne({email})
            if(candidate){
                return res.status(400).json({message:"this email already exists"})
            }
            const hashPass = await bcrypt.hash(password,5)
            const user = new User({email, password: hashPass})
            await user.save()
            return res.json({message:"User created"})
        }catch(e){
            console.log(e)
            res.send("error blyad")
        }
    }
)
routers.post(
    '/login',
    async (req,res)=>{
        try{
            const{email,password}=req.body
            const user = await User.findOne({email})
            if(!user){
                return res.status(404).json({message:"Email not found"})
            }
            const validPass= bcrypt.compareSync(password,user.password)
            if(!validPass){
                return res.status(400).json({message:"invalid password"})
            }
            const token = jwt.sign({id: user.id},config.get("jwtKey"),{expiresIn:"1h"})
            return res.json({
                token,
                user:{
                    id: user.id,
                    email: user.email,
                }
            })
        }catch(e){
            console.log(e)
            res.send("error blyad")
        }
    }
)
routers.get('/auth', authMiddleware,
    async (req, res) => {
        try {
            const user = await User.findOne({_id: req.user.id})
            const token = jwt.sign({id: user.id}, config.get("jwtKey"), {expiresIn: "1h"})
            return res.json({
                token,
                user: {
                    id: user.id,
                    email: user.email,
                }
            })
        } catch (e) {
            console.log(e)
            res.send({message: "Server error"})
        }
    })
module.exports = routers