<?php

namespace App\Domain\System\Infrastructure\Persistence\Repository;

use App\Domain\System\Domain\Contract\Repository\SystemStatusRepositoryInterface;
use App\Entity\Chapter;
use App\Entity\ContentSource;
use App\Entity\Manga;
use Doctrine\ORM\EntityManagerInterface;

class DoctrineSystemStatusRepository implements SystemStatusRepositoryInterface
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
    ) {
    }

    public function countMangas(): int
    {
        return (int) $this->entityManager
            ->createQuery('SELECT COUNT(m) FROM '.Manga::class.' m')
            ->getSingleScalarResult();
    }

    public function countMonitoredMangas(): int
    {
        return (int) $this->entityManager
            ->createQuery('SELECT COUNT(m) FROM '.Manga::class.' m WHERE m.monitored = true')
            ->getSingleScalarResult();
    }

    public function countMangasByStatus(): array
    {
        $results = $this->entityManager
            ->createQuery('SELECT m.status, COUNT(m) as cnt FROM '.Manga::class.' m GROUP BY m.status')
            ->getResult();

        $counts = [];
        foreach ($results as $row) {
            $status = $row['status'] ?? 'unknown';
            $counts[$status] = (int) $row['cnt'];
        }

        return $counts;
    }

    public function countChapters(): int
    {
        return (int) $this->entityManager
            ->createQuery('SELECT COUNT(c) FROM '.Chapter::class.' c')
            ->getSingleScalarResult();
    }

    public function countDownloadedChapters(): int
    {
        return (int) $this->entityManager
            ->createQuery('SELECT COUNT(c) FROM '.Chapter::class.' c WHERE c.cbzPath IS NOT NULL')
            ->getSingleScalarResult();
    }

    public function countContentSources(): int
    {
        return (int) $this->entityManager
            ->createQuery('SELECT COUNT(s) FROM '.ContentSource::class.' s')
            ->getSingleScalarResult();
    }

    public function countContentSourcesByHealth(): array
    {
        $results = $this->entityManager
            ->createQuery('SELECT s.healthStatus, COUNT(s) as cnt FROM '.ContentSource::class.' s GROUP BY s.healthStatus')
            ->getResult();

        $counts = [];
        foreach ($results as $row) {
            $counts[$row['healthStatus']] = (int) $row['cnt'];
        }

        return $counts;
    }
}
