<?php
namespace Mtc\Plugins\Agent\Providers;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Mtc\Plugins\Agent\database\seeders\AgentSettingsSeeder;
use Mtc\Plugins\Agent\Http\Middlewares\AgentAnonymous;
use Mtc\Plugins\Agent\Models\AgentSettings;

class AgentServiceProvider extends ServiceProvider {

    public function register() {
        $this->mergeConfigFrom(__DIR__ . '/../config/neuron.php', 'neuron');

        if (!config('neuron.enabled')) {
            return;
        }

        $this->loadRoutesFrom(__DIR__ . '/../routes/web.php');
        $this->loadMigrationsFrom(__DIR__ . '/../database/migrations');
    }

    public function boot(Router $router): void {
        $this->seedAgentSettings();

        $router->aliasMiddleware('agent.anonymous', AgentAnonymous::class);

        RateLimiter::for('agent-chat', function ($request) {
            return Limit::perMinute(10)->by($request->ip());
        });
    }

    protected function seedAgentSettings(): void {
        Cache::remember('agent_settings_seeded', 3600, function () {
            if (!Schema::hasTable('agent_settings')) {
                return false;
            }
            if (AgentSettings::count() === 0) {
                $seeder = new AgentSettingsSeeder();
                $seeder->run();
            }
            return true;
        });
    }

}
