class Provider::SessionsController < FrontendController

  layout 'provider/login'
  skip_before_action :login_required

  before_action :ensure_provider_domain
  before_action :find_provider

  def new
    redirect_to provider_admin_dashboard_url if logged_in?
    @session = Session.new
  end

  def create
    session_return_to
    logout_keeping_session!

    @user, strategy = authenticate_user

    if @user
      self.current_user = @user
      create_user_session!
      flash[:notice] = 'Signed in successfully'
      redirect_back_or_default provider_admin_path
    else
      @session = Session.new
      flash.now[:error] = strategy.error_message
      render :action => :new
    end
  end

  def destroy
    user = current_user
    logout_killing_session!
    destroy_user_session!
    if @provider.partner? && (logout_url = @provider.partner.logout_url)
      redirect_to logout_url + {user_id: user.id, provider_id: @provider.id}.to_query
    else
      redirect_to new_provider_sessions_path, notice: "You have been logged out."
    end
  end

  private

  def find_provider
    @provider ||= site_account_request.find_provider
  end

  def redirect_if_logged_in
    if logged_in? && current_account.provider?
      redirect_to provider_admin_dashboard_path
    end
  end

  def authenticate_user
    strategy = Authentication::Strategy::Internal.new(@provider, true)

    user = if request.post?
      strategy.authenticate(params.slice(:username, :password))
           elsif request.get?
      strategy.authenticate(params.slice(:token, :expires_at, :redirect_url))
    end

    [user, strategy]
  end

  def session_return_to
    if params[:return_to]
      return_to = safe_return_to(params[:return_to])
      session[:return_to] = return_to if return_to.present?
    end
  end
end
