const express = require("express");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../models/User");
const auth = require("../middleware/auth");
const { asyncHandler } = require("../middleware/errorHandler");
const {
  registerValidation,
  loginValidation,
} = require("../middleware/validators/authValidator");

const router = express.Router();

// Get user
router.get(
  "/",
  auth,
  asyncHandler(async (req, res) => {
    const user = await User.findById(req.user.id);
    if (!user) {
      return res.status(404).json({ msg: "User not found" });
    }
    res.json(user.toSafeObject());
  }),
);

// Register
router.post(
  "/register",
  registerValidation,
  asyncHandler(async (req, res) => {
    const { name, email, password } = req.body;

    let user = await User.findOne({ email });
    if (user) {
      return res.status(400).json({ success: false, msg: "User already exists" });
    }

    user = await User.create({
      name,
      email,
      password,
    });

    const payload = {
      user: {
        id: user._id,
      },
    };

    const token = await new Promise((resolve, reject) => {
      jwt.sign(
        payload,
        process.env.JWT_SECRET,
        { expiresIn: "7d" },
        (err, token) => {
          if (err) reject(err);
          else resolve(token);
        },
      );
    });

    res.json({ success: true, token });
  }),
);

// Login
router.post(
  "/login",
  loginValidation,
  asyncHandler(async (req, res) => {
    const { email, password } = req.body;

    let user = await User.findOne({ email });
    if (!user) {
      return res.status(400).json({ success: false, msg: "Invalid credentials" });
    }

    const isMatch = await user.comparePassword(password);
    if (!isMatch) {
      return res.status(400).json({ success: false, msg: "Invalid credentials" });
    }

    const payload = {
      user: {
        id: user._id,
      },
    };

    const token = await new Promise((resolve, reject) => {
      jwt.sign(
        payload,
        process.env.JWT_SECRET,
        { expiresIn: "7d" },
        (err, token) => {
          if (err) reject(err);
          else resolve(token);
        },
      );
    });

    res.json({ success: true, token });
  }),
);

module.exports = router;
