<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use App\Services\Messenger\EventDispatcher;

class MessengerServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton('messenger.events', function ($app) {
            return new EventDispatcher();
        });

        $this->app->alias('messenger.events', EventDispatcher::class);
    }

    public function boot(): void
    {
        $this->configureRateLimiting();
    }

    protected function configureRateLimiting(): void
    {
        // General messenger rate limits
        RateLimiter::for('messenger', function (Request $request) {
            return Limit::perMinute(120)->by($request->user()?->id ?: $request->ip());
        });

        // Message sending limits
        RateLimiter::for('messenger-send', function (Request $request) {
            return Limit::perMinute(30)->by($request->user()?->id ?: $request->ip());
        });

        // Conversation creation limits
        RateLimiter::for('messenger-create', function (Request $request) {
            return Limit::perMinute(10)->by($request->user()?->id ?: $request->ip());
        });

        // Typing indicator limits
        RateLimiter::for('messenger-typing', function (Request $request) {
            return Limit::perSecond(5)->by($request->user()?->id ?: $request->ip());
        });

        // Search limits
        RateLimiter::for('messenger-search', function (Request $request) {
            return Limit::perMinute(10)->by($request->user()?->id ?: $request->ip());
        });

        // Long-polling limits
        RateLimiter::for('messenger-longpoll', function (Request $request) {
            return Limit::perMinute(20)->by($request->user()?->id ?: $request->ip());
        });
    }
}
