# frozen_string_literal: true

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  skip_before_action :verify_authenticity_token

  def doorkeeper
    @user = User.from_omniauth(request.env["omniauth.auth"])

    @auth = request.env["omniauth.auth"]
    if @auth.info.role == "owner" || auth_user_has_access?
      @user = User.from_omniauth(@auth)
      if @user.persisted?
        @user.update_name_and_doorkeeper_credentials(@auth)
        session[:doorkeeper_user_id] = @user.id
        sign_in_and_redirect @user, event: :authentication
        set_flash_message(:notice, :success, kind: "Doorkeeper") if is_navigational_format?
      else
        session["devise.doorkeeper_data"] = request.env["omniauth.auth"]
        flash[:error] = t("generic_error") if is_navigational_format?
        redirect_to root_path
      end
    else
      redirect_to_auth_app_error_url
    end
  end

  def google_oauth2
    @user = User.from_omniauth(request.env["omniauth.auth"])

    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success", kind: "Google"
      sign_in_and_redirect @user, event: :authentication
    else
      session["devise.google_data"] = request.env["omniauth.auth"].except("extra") # Removing extra as it can overflow some session stores
      redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n")
    end
  end

  def failure
    redirect_to root_path
  end

  def auth_user_has_access?
    # Defaulting to true until we need to restrict users explictly for each app from neeto auth
    # Ref: https://github.com/bigbinary/neeto-auth-web/issues/644
    # return true if @auth.info.neeto_apps.length.zero?
    # return false !@auth.info.deactivated_at.nil?
    # (@auth.info.neeto_apps.find { |neeto_app| neeto_app.app_name == app_secrets.client_app_name }.present? && @auth.info.deactivated_at.nil?) || @auth.info.neeto_apps.length == 0
    true
  end

  def redirect_to_auth_app_error_url
    auth_uri = URI(app_secrets.auth_app[:url].gsub(app_secrets.app_subdomain, @organization.subdomain))
    auth_uri.path = "/error"
    auth_uri.query = URI.encode_www_form({ access: :denied })

    redirect_to(auth_uri.to_s)
  end

  def app_secrets
    @_app_secrets ||= Rails.application.secrets
  end
end
