const asyncHandler = require("express-async-handler");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const Feuser = require("../models/feuserModel");
const Response = require("../helpers/responseHelper");

//@access public
const registerUser = asyncHandler(async (req, res) => {
  const { first_name, last_name, mobile_number, password, user_role } =
    req.body;
  if (!first_name || !last_name || !mobile_number || !password || !user_role) {
    return Response.error(
      res,
      "VALIDATION_ERROR",
      "Please fill all required fields.",
      400,
    );
  }
  const userAvailable = await Feuser.findOne({ mobile_number });
  console.log(userAvailable);
  if (userAvailable) {
    return Response.error(res, "USER_EXISTS", "User already registered.", 400);
  }

  //Hash password
  const hashedPassword = await bcrypt.hash(password, 10);
  const feuser = await Feuser.create({
    first_name,
    last_name,
    mobile_number,
    password: hashedPassword,
    user_role,
  });
  if (feuser) {
    return Response.success(res, {
      _id: feuser.id,
      first_name: feuser.first_name,
      last_name: feuser.last_name,
      mobile_number: feuser.mobile_number,
      user_role: feuser.user_role,
    });
  } else {
    return Response.error(res, "CREATE_FAILED", "Failed to create user", 400);
  }
   return Response.success(res, { message: "User registered successfully" });
});

const currentUser = asyncHandler(async (req, res) => {
  return Response.success(res, req.user);
});

module.exports = { registerUser, currentUser };
