module Public
  class RegistrationsController < WebBaseController
    def new
      redirect_to public_team_dashboard_path(current_user.teams.first) if logged_in? && current_user.teams.any?
      @user = User.new
    end

    def create
      @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_dashboard_path(invitation.team), notice: "Benvenuto nella squadra!"
          end
        end
        redirect_to new_public_team_path, notice: "Account creato. Ora crea la tua squadra."
      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
