<?php

namespace App\Domain\Scraping\Infrastructure\Persistence;

use App\Domain\Scraping\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Scraping\Domain\Model\Manga;
use App\Domain\Scraping\Infrastructure\Persistence\Entity\MangaPreferredSourceEntity;
use App\Entity\Manga as EntityManga;
use App\Entity\ContentSource;
use Doctrine\ORM\EntityManagerInterface;

readonly class LegacyMangaRepository implements MangaRepositoryInterface
{
    public function __construct(
        private EntityManagerInterface $entityManager
    ) {
    }

    public function getById(string $id): ?Manga
    {
        /** @var EntityManga|null $mangaEntity */
        $mangaEntity = $this->entityManager->getRepository(EntityManga::class)->find($id);

        if (!$mangaEntity) {
            return null;
        }

        // Récupération des sources préférées avec l'ordre depuis la nouvelle entité
        $preferredSourceIds = [];
        $mangaPreferredSource = $this->entityManager->getRepository(MangaPreferredSourceEntity::class)
            ->findOneBy(['mangaId' => $mangaEntity->getId()]);

        if ($mangaPreferredSource) {
            $preferredSourceIds = $mangaPreferredSource->getOrderedSourceIds();
        }

        return new Manga(
            id: (string) $mangaEntity->getId(),
            title: $mangaEntity->getTitle(),
            slug: $mangaEntity->getSlug(),
            description: $mangaEntity->getDescription() ?? '',
            author: $mangaEntity->getAuthor() ?? '',
            publicationYear: (string) ($mangaEntity->getPublicationYear() ?? ''),
            monitored: $mangaEntity->isMonitored() ?? false,
            preferredSources: $preferredSourceIds,
            alternativeSlugs: $mangaEntity->getAlternativeSlugs() ?? []
        );
    }

    public function updatePreferredSources(string $mangaId, array $sourceIds): void
    {
        /** @var EntityManga|null $mangaEntity */
        $mangaEntity = $this->entityManager->getRepository(EntityManga::class)->find($mangaId);

        if (!$mangaEntity) {
            throw new \InvalidArgumentException("Manga not found with ID: {$mangaId}");
        }

        // Récupérer ou créer l'entité MangaPreferredSource
        $mangaPreferredSource = $this->entityManager->getRepository(MangaPreferredSourceEntity::class)
            ->findOneBy(['mangaId' => (int) $mangaId]);

        if (!$mangaPreferredSource) {
            $mangaPreferredSource = new MangaPreferredSourceEntity();
            $mangaPreferredSource->setMangaId((int) $mangaId);
        }

        // Si pas de sources, vider les sources préférées
        if (empty($sourceIds)) {
            $mangaPreferredSource->setOrderedSourceIds([]);
        } else {
            // Valider que toutes les sources existent avant de les sauvegarder
            $sources = $this->entityManager->getRepository(ContentSource::class)->findBy(['id' => $sourceIds]);
            $existingSourceIds = array_map(fn ($source) => (string) $source->getId(), $sources);

            // Garder uniquement les sources qui existent et maintenir l'ordre
            $validSourceIds = array_values(array_intersect($sourceIds, $existingSourceIds));

            $mangaPreferredSource->setOrderedSourceIds($validSourceIds);
        }

        $this->entityManager->persist($mangaPreferredSource);
        $this->entityManager->flush();
    }
}
