<?php

namespace App\Repository;

use App\Entity\Service;
use App\Entity\ServiceStatusHistory;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @extends ServiceEntityRepository<Service>
 *
 * @codeCoverageIgnore
 */
class ServiceRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Service::class);
    }

    /**
     * @return list<ServiceStatusHistory>
     */
    public function getHistoryForDays(Service $service, int $days = 30): array
    {
        $since = new \DateTimeImmutable('-'.$days.' days');

        return $this->getEntityManager()
            ->getRepository(ServiceStatusHistory::class)
            ->createQueryBuilder('h')
            ->where('h.service = :service')
            ->andWhere('h.createdAt >= :since')
            ->setParameter('service', $service)
            ->setParameter('since', $since)
            ->orderBy('h.createdAt', 'DESC')
            ->getQuery()
            ->getResult();
    }

    /**
     * Retourne les données pour le graphique uptime 30 jours.
     *
     * @return list<array{date: string, status: string}>
     */
    public function getDailyStatus(Service $service, int $days = 30): array
    {
        $history = $this->getHistoryForDays($service, $days);
        $result = [];
        $now = new \DateTimeImmutable();

        for ($i = $days - 1; $i >= 0; --$i) {
            $date = $now->modify('-'.$i.' days');
            $dateStr = $date->format('Y-m-d');
            $dayStatus = 'up';

            foreach ($history as $entry) {
                if ($entry->getCreatedAt()->format('Y-m-d') === $dateStr) {
                    $dayStatus = $entry->getStatus();
                    break;
                }
            }

            $result[] = [
                'date' => $dateStr,
                'status' => $dayStatus,
            ];
        }

        return $result;
    }
}
