module Public
  class RegistrationsController < WebBaseController
    def new
      redirect_to public_club_path(current_user.primary_club) if logged_in? && current_user.primary_club
      @user = User.new
    end

    def create
      unless params[:accept_terms] == "1"
        @user = User.new(user_params.merge(role: "coach"))
        flash.now[:alert] = "Devi accettare l’informativa privacy e i termini di servizio per registrarti."
        return render :new, status: :unprocessable_entity
      end

      @user = User.new(user_params.merge(role: "coach"))
      if @user.save
        session[:user_id] = @user.id
        if session[:pending_invite_token].present?
          token = session.delete(:pending_invite_token)
          invitation = TeamInvitation.pending.find_by(token_digest: Digest::SHA256.hexdigest(token))
          if invitation && invitation.email.downcase == @user.email.downcase
            invitation.accept!(@user)
            return redirect_to public_team_details_path(invitation.team), notice: "Benvenuto nella squadra!"
          end
        end
        redirect_to public_new_club_path, notice: "Account creato. Ora registra la tua società."
      else
        flash.now[:alert] = @user.errors.full_messages.join(", ")
        render :new, status: :unprocessable_entity
      end
    end

    private

    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation)
    end
  end
end
