<?php

namespace App\Console\Commands;

use App\Services\BusinessUserService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

class TestApiConnection extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'api:test {endpoint?} {--timeout=30}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Probar la conexión con la API externa';

    protected BusinessUserService $businessUserService;

    public function __construct(BusinessUserService $businessUserService)
    {
        parent::__construct();
        $this->businessUserService = $businessUserService;
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $endpoint = $this->argument('endpoint');
        $timeout = $this->option('timeout');

        $this->info('🔄 Probando conexión con la API...');
        $this->info('📍 URL Base: ' . config('api.base_url'));
        $this->newLine();

        if ($endpoint) {
            $this->testSpecificEndpoint($endpoint);
        } else {
            $this->testAllEndpoints();
        }
    }

    protected function testSpecificEndpoint(string $endpoint)
    {
        $this->info("🎯 Probando endpoint: {$endpoint}");
        
        try {
            // Probar conexión básica
            $result = $this->businessUserService->checkConnection();
            
            if ($result['success']) {
                $this->info('✅ Conexión exitosa');
                $this->line('📦 Status: ' . $result['status_code']);
                $this->line('📦 Mensaje: ' . $result['message']);
            } else {
                $this->error('❌ Conexión fallida');
                $this->line('📦 Error: ' . ($result['error'] ?? 'Error desconocido'));
            }
        } catch (\Exception $e) {
            $this->error('💥 Error: ' . $e->getMessage());
        }
    }

    protected function testAllEndpoints()
    {
        $endpoints = [
            'API Health Check' => $this->businessUserService->checkConnection(),
        ];

        $results = [];

        foreach ($endpoints as $name => $response) {
            $this->info("🔍 Probando: {$name}");
            
            try {
                if (isset($response['success']) && $response['success']) {
                    $this->info('  ✅ OK');
                    $results[$name] = 'OK';
                } else {
                    $this->warn('  ⚠️  Respuesta no exitosa');
                    $results[$name] = 'WARNING';
                }
            } catch (\Exception $e) {
                $this->error('  ❌ Error: ' . $e->getMessage());
                $results[$name] = 'ERROR';
            }
            
            $this->newLine();
        }

        // Probar URLs específicas usando helpers
        $specificTests = [
            'Business Create User URL' => api_url('business.create_user'),
            'Business List Users URL' => api_url('business.list_users'),
            'Health URL' => api_url('system.health'),
        ];

        foreach ($specificTests as $name => $url) {
            $this->info("🔍 Verificando URL: {$name}");
            $this->line("   📍 {$url}");
            
            try {
                $response = Http::timeout(10)->get($url);
                
                if ($response->successful()) {
                    $this->info('  ✅ URL accesible');
                    $results[$name] = 'OK';
                } else {
                    $this->warn("  ⚠️  Status: {$response->status()}");
                    $results[$name] = 'WARNING';
                }
            } catch (\Exception $e) {
                $this->error('  ❌ Error: ' . $e->getMessage());
                $results[$name] = 'ERROR';
            }
            
            $this->newLine();
        }

        // Resumen
        $this->newLine();
        $this->info('📊 RESUMEN DE PRUEBAS:');
        $this->newLine();
        
        foreach ($results as $name => $status) {
            $icon = match($status) {
                'OK' => '✅',
                'WARNING' => '⚠️',
                'ERROR' => '❌',
                default => '❓'
            };
            
            $this->line("{$icon} {$name}: {$status}");
        }

        $okCount = count(array_filter($results, fn($status) => $status === 'OK'));
        $totalCount = count($results);
        
        $this->newLine();
        if ($okCount === $totalCount) {
            $this->info("🎉 Todas las pruebas pasaron ({$okCount}/{$totalCount})");
        } else {
            $this->warn("⚠️  {$okCount}/{$totalCount} pruebas pasaron");
        }
    }
}