<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Client\RequestException;
use InvalidArgumentException; // Importar la clase de excepción

class BlulincApiService
{
    protected $baseUrl;
    protected $apiToken;

    public function __construct()
    {
        $this->baseUrl = rtrim(config('services.blulinc.url'), '/');
        $this->apiToken = config('services.blulinc.token');

        // --- INICIO DE LA MEJORA ---
        // Verificamos que la URL base y el token se hayan cargado correctamente.
        // Esto previene el error "Could not resolve host" si la configuración falta.
        if (empty($this->baseUrl)) {
            throw new InvalidArgumentException('Blulinc API URL is not configured. Please check your .env file for BLULINC_API_URL.');
        }
        if (empty($this->apiToken)) {
            throw new InvalidArgumentException('Blulinc API Token is not configured. Please check your .env file for BLULINC_API_TOKEN.');
        }
        // --- FIN DE LA MEJORA ---
    }

    private function makeRequest(string $endpoint, array $queryParams = []): ?array
    {
        $fullUrl = $this->baseUrl . $endpoint;

        try {
            $response = Http::withToken($this->apiToken)
                ->acceptJson()
                ->timeout(60)
                ->retry(3, 1000)
                ->get($fullUrl, $queryParams);

            // Registramos SIEMPRE la respuesta para poder depurar.
            Log::debug("BlulincApiService: API Response from {$endpoint}", [
                'status' => $response->status(),
                'body' => $response->body(), // Registramos el cuerpo completo
            ]);

            // Lanza una excepción para respuestas 4xx/5xx
            $response->throw();

            return $response->json();

        } catch (RequestException $e) {
            Log::error("BlulincApiService: RequestException for {$endpoint}", [
                'url' => $fullUrl,
                'status' => $e->response ? $e->response->status() : 'N/A',
                'message' => $e->getMessage()
            ]);
        } catch (\Exception $e) {
            Log::error("BlulincApiService: General error for {$endpoint}", [
                'url' => $fullUrl,
                'message' => $e->getMessage()
            ]);
        }

        return null;
    }

    public function getPartners(int $page = 1, int $perPage = 100): ?array
    {
        $cacheKey = "blulinc.partners.page.{$page}.perpage.{$perPage}";
        
        return Cache::remember($cacheKey, now()->addMinutes(10), function () use ($page, $perPage) {
            return $this->makeRequest('/partners/v2.0', [
                'page' => $page,
                'per_page' => $perPage
            ]);
        });
    }

    public function getPartnerInvites(int $page = 1, int $perPage = 100): ?array
    {
        $cacheKey = "blulinc.partner_invites.page.{$page}.perpage.{$perPage}";

        return Cache::remember($cacheKey, now()->addMinutes(5), function () use ($page, $perPage) {
            return $this->makeRequest('/partner-invites/v1.0', [
                'page' => $page,
                'per_page' => $perPage
            ]);
        });
    }
        /**
     * Obtiene un partner específico por su ID.
     *
     * @param int $partnerId
     * @return array|null
     */
    public function getPartnerById(int $partnerId): ?array
    {
        $cacheKey = "blulinc.partner.id.{$partnerId}";
        
        // Caché por un día, ya que los datos de un partner específico no cambian a menudo.
        return Cache::remember($cacheKey, now()->addDay(), function () use ($partnerId) {
            $response = $this->makeRequest("/partners/v2.0/{$partnerId}");
            // La respuesta de un solo item suele venir dentro de una clave 'data'.
            return $response['data'] ?? null;
        });
    }
}
