<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;

class StreamiService
{
    private string $baseUrl = 'https://streamed.pk/api';

    public function getLiveMatches(): array
    {
        return $this->fetchFromApi('/matches/live', 'streami_live', 60);
    }

    public function getTodayMatches(): array
    {
        return $this->fetchFromApi('/matches/all-today', 'streami_today', 300);
    }

    public function getAllMatches(): array
    {
        return $this->fetchFromApi('/matches/all', 'streami_all', 300);
    }

    private function fetchFromApi(string $endpoint, string $cacheKey, int $duration): array
    {
        return Cache::remember($cacheKey, $duration, function () use ($endpoint) {
            try {
                $response = Http::withUserAgent('Mozilla/5.0')->get($this->baseUrl . $endpoint);
                
                if ($response->successful()) {
                    return $response->json();
                }
            } catch (\Exception $e) {
                // Log error or fail silently
            }

            return [];
        });
    }

    public function getMatchById(string $id): ?array
    {
        // Try to find in caches first without making new requests if possible
        $caches = ['streami_live', 'streami_today', 'streami_all'];
        
        foreach ($caches as $key) {
            $matches = Cache::get($key);
            if ($matches) {
                foreach ($matches as $match) {
                    if (isset($match['id']) && $match['id'] === $id) {
                        return $match;
                    }
                }
            }
        }

        // If not in cache, we might want to fetch fresh 'all' matches
        // But for now let's reuse getAllMatches which handles caching
        $matches = $this->getAllMatches();
        foreach ($matches as $match) {
            if (isset($match['id']) && $match['id'] === $id) {
                return $match;
            }
        }

        return null;
    }

    public function getStream(string $source, string $id): ?array
    {
        $url = "/stream/{$source}/{$id}";
        try {
            $response = Http::withUserAgent('Mozilla/5.0')->get($this->baseUrl . $url);
            if ($response->successful()) {
                return $response->json();
            }
        } catch (\Exception $e) {
            // Log error
        }
        return null;
    }
}
