<?php

namespace Inside\IIDE\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Inside\Content\Models\Contents\ProjectNews;
use Inside\Content\Models\Contents\Subsidiaries;
use Inside\Host\Bridge\BridgeContent;
use Inside\RSS\Helpers\RssFeeder;
use Symfony\Component\Config\Util\Exception\XmlParsingException;

class ImportProjectNewsFromRss extends Command
{
    /**
     * @var string
     */
    protected $name = 'iide:project-news:import';

    /**
     * @var string
     */
    protected $signature = 'iide:project-news:import';

    /**
     * @var string
     */
    protected $description = 'Import des actualités des projets depuis le flux RSS';

    /**
     * @var string[]
     */
    private $fields;

    /**
     * @var array
     */
    private $filters;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        $this->fields = explode(',', env('IIDE_FEED_RSS_FIELDS', ''));
        $this->filters = ["source" => true];
    }

    public function handle(): void
    {
        Subsidiaries::query()
            ->whereNotNull('rss')
            ->get(['uuid', 'rss', 'title', 'langcode'])
            ->each(fn ($subsidiary) => $this->importFeedRss(
                uuid: $subsidiary->uuid,
                rss: $subsidiary->rss,
                title: $subsidiary->title,
                langcode: $subsidiary->langcode,
            ));
    }

    private function importFeedRss(string $uuid, string $rss, string $title, string $langcode): void
    {
        $bridge = new BridgeContent();
        $feeder = new RssFeeder($rss, $this->fields, $this->filters);

        try {
            $data = $feeder->feed();
        } catch (XmlParsingException) {
            $this->getOutput()->writeln("<fg=red>[$langcode] there is a problem with the flux of $title x</fg=red>");

            return;
        }

        $alreadyImported = ProjectNews::query()
            ->whereHas('subsidiaries', fn ($query) => $query->where('uuid', $uuid))
            ->pluck('title');

        $imported = collect($data)
            ->reject(static fn (array $news) => $alreadyImported->contains($news['title']))
            ->each(static fn (array $news) => $bridge->contentInsert(
                type: 'project_news',
                data: [
                    'type' => 'node',
                    'bundle' => 'project_news',
                    'langcode' => $langcode,
                    'title' => $news['title'],
                    'project_news_content' => $news['content'],
                    'chapo' => $news['description'],
                    'image_link' => $news['image'],
                    'news_fr_id' => $news['id_fr'] ?? '',
                    'news_en_id' => $news['id_en'] ?? '',
                    'uri' => $news['link'],
                    'subsidiaries' => $uuid,
                    'published_at' => Carbon::createFromTimestamp($news['pubDate'])->toDateTimeString()
                ]
            ))
            ->count();

        $this->getOutput()->writeln(
            "<fg=yellow>[$langcode] $title - $imported news imported ✔</fg=yellow>"
        );
    }
}
