<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;

class NewsController extends Controller
{
    public function search(Request $request): JsonResponse
    {
        $request->validate([
            'q' => 'required|string|min:2|max:100',
        ]);

        $response = Http::timeout(10)
            ->withOptions([
                // Avoid local SSL issues while keeping verification in non-local envs.
                'verify' => !app()->environment('local'),
            ])
            ->get('https://newsapi.org/v2/everything', [
                'q'        => $request->query('q'),
                'pageSize' => 6,
                'sortBy'   => 'publishedAt',
                'language' => 'en',
                'apiKey'   => config('services.newsapi.key'),
            ]);

        if ($response->failed()) {
            return response()->json(['error' => 'Failed to fetch news. Please try again.'], 502);
        }

        $data = $response->json();

        if (($data['status'] ?? '') !== 'ok') {
            return response()->json(['error' => $data['message'] ?? 'Unknown error from news provider.'], 502);
        }

        $articles = collect($data['articles'])
            ->filter(fn($a) =>
                !empty($a['title']) &&
                !empty($a['url']) &&
                $a['title'] !== '[Removed]'
            )
            ->values()
            ->take(6);

        return response()->json(['articles' => $articles]);
    }
}
