import _RS from "../helpers/ResponseHelper";
import Auth from "../Utils/Auth";
import Admin from "../models/Admin";
import User from "../models/User";
import { getLanguageStrings } from "../locale";
// import Admin from "../models/adminModel"

class Authentication {
  constructor() {}

  static async userLanguage(req, res, next) {   
    const language    =   req.user.language ?? "en";
    const lang        =   getLanguageStrings(language);
    req.lang          =   lang;
    next();
  }

  static async user(req, res, next) {
    const startTime = new Date().getTime();
    try {
      let token;

      if (req.headers.authorization && req.headers.authorization.startsWith("Bearer")) {
        token = req.headers.authorization.split(" ")[1];
      }

      if (!token) {
        return _RS.api( res, false, "Un-Authorized User", {}, startTime );
      }

      const decoded: any = await Auth.decodeJwt(token);
      const currentUser = await User.findById(decoded._id);

      if (!currentUser) {
        return _RS.api( res, false, "User doesn\'t exists with us", {}, startTime );
      }

      if (!currentUser.is_active) {
        return _RS.unAuthorize( res, "FORBIDDEN", "Account Deactivated Please contact to admin", {}, startTime );
      }

      req.user = currentUser;
      req.user.id = decoded.id;
      next();
    } catch (err) {
      return next(err);
    }
  }

  static async admin(req, res, next) {
    const startTime = new Date().getTime();
    try {
      let token;

      if (req.headers.authorization && req.headers.authorization.startsWith("Bearer")) {
        token = req.headers.authorization.split(" ")[1];
      }

      if (!token) {
        return _RS.unAuthenticated( res, "UNAUTHORIZE", "UNAUTHORIZE", {}, startTime, 0 );
      }

      const decoded: any = await Auth.decodeJwt(token);

      const currentUser = await Admin.findById(decoded.id);

      if (!currentUser) {
        return _RS.notFound( res, "NOTFOUND", "Credentials are not match with us", currentUser, startTime );
      }

      req.user = currentUser;
      req.user.id = decoded.id;
      next();
    } catch (err) {
      return next(err);
    }
  }

}

export default Authentication;
