const { hash } = require("bcryptjs");
const bcrypt = require("bcryptjs");
const authDbService = require("../services/authDbService");
const jwt = require("jsonwebtoken");

const register = async (req, res) => {
  try {
    const { User_Name, Password, Email, Contact_No } = req.body;

    const user_availability = await authDbService.checkUser(Email);
    if (user_availability.length === 0) {
      bcrypt.hash(Password, 10, async (err, hash) => {
        if (err) {
          return res.status(401).json({ Error: "Error hasing password ", err });
        }
        try {
          const new_user = await authDbService.register(
            User_Name,
            hash,
            Email,
            Contact_No
          );
          const insertedID = new_user.insertId;
          const defaultVal = 0;
          // await userPrevilageDbService.addUserPrevilage(
          //   insertedID,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal,
          //   defaultVal
          // );

          return res
            .status(201)
            .json({ message: "User registration completed!" });
        } catch (err) {
          res.status(401).json({
            message: "Somthing went wrong when inserting the user!",
            error: err,
          });
        }
      });
    } else {
      res
        .status(500)
        .json({ message: "The email is already registered in the system!" });
    }
  } catch (err) {
    res.status(500).json({
      message: "Somthing went wrong when registering the user!",
      error: err.message,
    });
  }
};

const checkToken = async (req, res) => {
  if (req.idUser) {
    res.status(200).json({
      Status: `Authentication Success. Token is valid. The user id is ${req.idUser}`,
    });
  } else {
    res
      .status(500)
      .json({ Status: "Authentication is not valid! Token is not valid!" });
  }
};

const login = async (req, res) => {
  try {
    const { Email, Password } = req.body; // 'Email' may contain email or contact number

    // Check if the input is an email or contact number
    const isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Email); // Simple regex for email
    const user_check = await authDbService.checkUser(Email, isEmail);

    if (user_check.length === 0) {
      return res.status(500).json({
        message: "The email/contact number you entered is not registered!",
      });
    }

    const user = user_check[0];

    const passwordMatch = await bcrypt.compare(Password, user.Password);
    if (!passwordMatch) {
      return res
        .status(500)
        .json({ message: "The password you entered is not correct!" });
    }

    const token = jwt.sign({ idUser: user.idUser }, "secret_key");
    // const user_previlages = await userPrevilageDbService.getUsersPrivileges(
    //   user.Role
    // );
    res.cookie("_auth", token, {
      httpOnly: true, // Prevent client-side JavaScript from accessing the cookie
      secure: false, // Use false for localhost (non-HTTPS)
      sameSite: "strict", // Prevent CSRF
      maxAge: 3600000, // 1 hour
    });

    res.status(200).json({
      token,
      user: {
        email: user.Email,
        userId: user.idUser,
        name: user.User_Name,
        // Employee_idEmployee: user.Employee_idEmployee,
        // user_previlages: user_previlages[0],
      },
    });
  } catch (err) {
    res.status(500).json({
      Status: "Something went wrong in the login process!",
      error: err.message,
    });
  }
};

module.exports = {
  register,
  checkToken,
  login,
};
