module Public
  class SessionsController < WebBaseController
    def new
      if logged_in? && current_user.primary_club
        redirect_to public_club_path(current_user.primary_club)
      end
    end

    def create
      user = User.find_by(email: params[:email]&.downcase)
      if user&.authenticate(params[:password])
        session[:user_id] = user.id
        dest = if user.primary_club
                 public_club_path(user.primary_club)
               elsif user.manageable_teams.first
                 public_team_details_path(user.manageable_teams.first)
               else
                 public_new_club_path
               end
        redirect_to dest, notice: "Bentornato!"
      else
        flash.now[:alert] = "Email o password non validi"
        render :new, status: :unauthorized
      end
    end

    def destroy
      reset_session
      redirect_to public_pricing_path, notice: "Disconnesso"
    end
  end
end
