module Public
  class SessionsController < WebBaseController
    def new
      redirect_to public_team_dashboard_path(current_user.teams.first) if logged_in? && current_user.teams.any?
    end

    def create
      user = User.find_by(email: params[:email]&.downcase)
      if user&.authenticate(params[:password])
        session[:user_id] = user.id
        dest = user.teams.first ? public_team_dashboard_path(user.teams.first) : new_public_team_path
        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
