/*****  Packages  *****/
import Joi from "joi";
import bcrypt from "bcrypt";
import _ from "lodash";

/*****  Modules  *****/
import { User } from "#models/user_model";
import asyncHandler from "#middlewares/asyncHandler";

/**
 @desc     User Login
 @route    POST /api/auth
 @access   Public
 */
const validate = (req) => {
  const schema = Joi.object({
    email: Joi.string().required().email(),
    password: Joi.string().min(8).max(255).required(),
  });

  return schema.validate(req);
};

const loginUser = asyncHandler(async (req, res) => {
  console.log("this is testing", req);
  const { error } = validate(req.body);
  if (error) {
    return res
      .status(400)
      .send({ status: false, message: error?.details[0]?.message });
  }

  let user = await User.findOne({ email: req.body.email });
  if (!user) return res.status(400).send("Invalid email or password.");

  const validPassword = await bcrypt.compare(req.body.password, user.password);
  if (!validPassword) return res.status(400).send("Invalid email or password.");

  if (!user.isVerified) return res.status(400).send("Please verified Email First");

  const token = user.generateAuthToken();

  return res
    .cookie("x-auth-token", token, {
      httpOnly: true,
      maxAge: 365 * 24 * 60 * 60 * 1000,
      site: "none"
    }) // maxAge expire after 1 hour
    .header("x-auth-token", token)
    .header("access-control-expose-headers", "x-auth-token")
    .status(200)
    .send({
      status: true,
      message: "User Login successfully",
      user: user,
    });

});

/**
 @desc     Clear Cookies
 @route    GET /api/auth/logout
 @access   Public
 */

const logout = asyncHandler(async (req, res) => {
  res.cookie("x-auth-token", null).send("Successfully logout");
});

export { loginUser, logout };