<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Services\NewsApiService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class NewsApiController extends Controller
{
    private NewsApiService $newsApiService;

    public function __construct(NewsApiService $newsApiService)
    {
        $this->newsApiService = $newsApiService;
    }

    /**
     * Handle NewsAPI requests
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function index(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'type' => ['required', 'string', 'in:everything,top-headlines,sources'],
        ]);

        $type = $validated['type'];
        $params = $request->except(['type']);

        try {
            $data = match ($type) {
                'everything' => $this->newsApiService->getEverything($params),
                'top-headlines' => $this->newsApiService->getTopHeadlines($params),
                'sources' => $this->newsApiService->getSources($params),
            };

            return response()->json([
                'status' => 'success',
                'data' => $data,
            ]);
        } catch (\RuntimeException $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage(),
            ], 500);
        }
    }
}
