<?php

namespace App\Services;

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

class NewsDataService
{
    protected $apiKey;
    protected $apiUrl;
    protected $cacheTtl;

    public function __construct()
    {
        $this->apiKey = config('services.newsdata.api_key');
        $this->apiUrl = config('services.newsdata.api_url', 'https://newsdata.io/api/1');
        $this->cacheTtl = config('services.newsdata.cache_ttl', 3600);
    }

    /**
     * Search for legal news
     */
    public function searchLegalNews($query, $limit = 10)
    {
        $cacheKey = 'newsdata:search:' . md5($query . $limit);

        return Cache::remember($cacheKey, $this->cacheTtl / 60, function () use ($query, $limit) {
            return $this->makeRequest('latest', [
                'q' => $query,
                'category' => 'law,politics',
                'size' => $limit,
                'removeduplicate' => 1,
            ]);
        });
    }

    /**
     * Get latest legal news
     */
    public function getLatestLegalNews($limit = 10)
    {
        $cacheKey = 'newsdata:latest:' . $limit;

        return Cache::remember($cacheKey, $this->cacheTtl, function () use ($limit) {
            return $this->makeRequest('latest', [
                'category' => 'law,politics',
                'size' => $limit,
                'removeduplicate' => 1,
            ]);
        });
    }

    /**
     * Make HTTP request to NewsData.io API
     */
    public function makeRequest($endpoint, $params = [])
    {
        try {
            $url = $this->apiUrl . '/' . $endpoint;
            $params['apikey'] = $this->apiKey;

            $response = Http::timeout(10)->get($url, $params);

            if ($response->successful()) {
                return $this->transformResponse($response->json());
            } else {
                $this->handleError(new \Exception('API request failed with status: ' . $response->status()));
                return [
                    'success' => false,
                    'articles' => [],
                    'total' => 0
                ];
            }
        } catch (\Exception $e) {
            $this->handleError($e);
            return [
                'success' => false,
                'articles' => [],
                'total' => 0
            ];
        }
    }

    /**
     * Transform API response to our format
     */
    protected function transformResponse($apiResponse)
    {
        $articles = collect($apiResponse['results'] ?? [])->map(function ($article) {
            return [
                'title' => $article['title'] ?? 'No Title',
                'description' => $article['description'] ?? 'No description available',
                'source' => $article['source_id'] ?? 'Unknown Source',
                'publishedAt' => isset($article['pubDate']) ?
                    Carbon::parse($article['pubDate'])->format('M d, Y') : 'Unknown Date',
                'url' => $article['link'] ?? '#',
                'category' => $article['category'] ?? ['Legal News']
            ];
        })->toArray();

        return [
            'success' => true,
            'articles' => $articles,
            'total' => count($articles)
        ];
    }

    /**
     * Handle API errors gracefully
     */
    protected function handleError($exception)
    {
        Log::error('NewsData.io API Error: ' . $exception->getMessage(), [
            'exception' => $exception,
            'api_key_configured' => !empty($this->apiKey),
            'api_url' => $this->apiUrl
        ]);
    }
}
