class MobileAppApi::V1::AuthenticationController < MobileAppApi::V1::BaseController

  # Api to authenticate and create session of user when login
  def mobile_app_authentication
    if params[:provider]
      unless ['facebook', 'linkedin'].include? params[:provider]
        render json: { status: 400 , providers: ['facebook', 'linkedin'], error: "invalid provider" } and return
      end
      #temporary code for Miceal till he finishes registration process
      authentication = Authentication.find_by(provider: params[:provider], uid: params[:uid])
      if authentication and authentication.user
        user = authentication.user
      else
        render json: { status: 404 , error: "User not registered." } and return
      end
#      auth = Authentication.create_omniauth_object(params[:provider], params[:token], params[:uid])
#      unless auth.is_a? OmniAuth::AuthHash
#        render json: auth.merge(status: 400) and return
#      end
#      @authentication = Authentication.find_or_create_with_omniauth(auth)
#      @authentication.build_user_with_omniauth(params[:email])
#      if @authentication.has_valid_user_email? and @authentication.save(validate: false)
#        @authentication.user
#      else
#        render json: { status: 400 , allowed_domains: Configurations::General.domain_list, error: "Email address is not valid or not allowed" } and return
#      end
    else
      user = login params[:email], params[:password]
    end
    if user and user.active?
      render json: { status: 200 , auth_token: user.generate_auth_token, user_info: user.info }
    else
      user = User.find_by(email: params[:email])
      if user and !user.active?
        render json: { status: 400 , error: "Kindly activate your account from your registered email address, using activation email sent to you." }
      else
        render json: { status: 400 , error: "Login failed. Please try again with valid credentials." }
      end
    end
  end

  # Api to destroy session of user when log out
  def mobile_app_logout
    user = User.where(auth_token: params[:auth_token])
    if !user.nil? && !user[0].nil?
      user[0].destroy_auth_token
      render json: { status: 200, message: "Successfully Logged Out." }
    else
      render json: { status: 400 , error: "No user found with provided auth_token." }
    end
  end

  # Api for password recovery
  def forgot_password
    user = User.where(email: params[:email])
    if !user.nil? && !user[0].nil?
      user[0].deliver_reset_password_instructions!
      render json: { status: 200 , success: "Password reset instructions has been sent on #{params[:email]} email address. Please check your mailbox."}
    else
      render json: { status: 400 , error: "No user found with email #{params[:email]}"}
    end
  end

end
