<?php

namespace App\Domain\Setting\Application\CommandHandler;

use App\Domain\Setting\Application\Command\ImportContentSourceCommand;
use App\Domain\Setting\Domain\Contract\Repository\ContentSourceRepositoryInterface;
use App\Domain\Setting\Domain\Model\ContentSource;
use InvalidArgumentException;

readonly class ImportContentSourceCommandHandler
{
    public function __construct(
        private ContentSourceRepositoryInterface $contentSourceRepository
    ) {
    }

    public function handle(ImportContentSourceCommand $command): void
    {
        // Validation des données d'import
        if (!is_array($command->contentSources)) {
            throw new InvalidArgumentException('Content sources must be an array');
        }

        foreach ($command->contentSources as $data) {
            if (!$this->isValidContentSourceData($data)) {
                throw new InvalidArgumentException('Invalid content source data provided');
            }

            // Recherche d'une source existante avec la même baseUrl
            $existingContentSource = $this->contentSourceRepository->findByBaseUrl($data['baseUrl']);

            if ($existingContentSource) {
                // Met à jour la source existante
                $existingContentSource->update(
                    baseUrl: $data['baseUrl'],
                    chapterUrlFormat: $data['chapterUrlFormat'],
                    scrapingType: $data['scrapingType'],
                    imageSelector: $data['imageSelector'] ?? null,
                    nextPageSelector: $data['nextPageSelector'] ?? null,
                    chapterSelector: $data['chapterSelector'] ?? null,
                );

                $this->contentSourceRepository->save($existingContentSource);
            } else {
                // Crée une nouvelle source
                $newContentSource = ContentSource::create(
                    baseUrl: $data['baseUrl'],
                    chapterUrlFormat: $data['chapterUrlFormat'],
                    scrapingType: $data['scrapingType'],
                    imageSelector: $data['imageSelector'] ?? null,
                    nextPageSelector: $data['nextPageSelector'] ?? null,
                    chapterSelector: $data['chapterSelector'] ?? null,
                );

                $this->contentSourceRepository->save($newContentSource);
            }
        }
    }

    private function isValidContentSourceData(mixed $data): bool
    {
        if (!is_array($data)) {
            return false;
        }

        $requiredFields = ['baseUrl', 'chapterUrlFormat', 'scrapingType'];
        foreach ($requiredFields as $field) {
            if (!isset($data[$field]) || !is_string($data[$field]) || empty($data[$field])) {
                return false;
            }
        }

        return true;
    }
}
