<?php

namespace OtomaticAi\Controllers\SingleMode;

use Exception;
use OtomaticAi\Controllers\Controller;
use OtomaticAi\Utils\RSS\Reader;

class RssSourceController extends Controller
{
    public function search()
    {
        $this->validate([
            "url" => ["required", "url"],
        ]);

        try {
            $rss = Reader::load($this->input("url"));

            $items = [];
            foreach ($rss->items as $item) {

                $url = (string) $item->url;
                $title = (string) $item->title;

                $items[] = [
                    "title" => $title,
                    "url" => $url,
                ];
            }

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