<?php

namespace OtomaticAi\Controllers\SingleMode;

use Exception;
use OtomaticAi\Controllers\Controller;
use OtomaticAi\Utils\GoogleNews;
use OtomaticAi\Utils\Language;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

class NewsSourceController extends Controller
{
    public function search()
    {
        $this->validate([
            "query" => ["required", "string"],
            "language" => ["required", "string"],
        ]);

        try {
            $items = GoogleNews::search($this->input('query'), Language::find($this->input('language', 'en')));

            $items = Arr::map($items, function ($item) {
                $title = $item["title"];
                $url = $item["url"];

                return [
                    "title" => $title,
                    "url" => $url,
                ];
            });

            $this->response($items);
        } catch (Exception $e) {
            $this->response(["message" => "An error occurred", "error" => $e->getMessage()], 503);
        }
    }
}
