<?php

namespace App\Controller;

use App\Entity\ServiceMessage;
use App\Repository\ServiceCategoryRepository;
use App\Repository\ServiceRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class StatusPageController extends AbstractController
{
    #[Route('/status', name: 'app_status')]
    public function index(ServiceCategoryRepository $categoryRepository, ServiceRepository $serviceRepository, EntityManagerInterface $em): Response
    {
        $categories = $categoryRepository->findBy([], ['position' => 'ASC']);

        $servicesData = [];
        $globalStatus = 'up';

        foreach ($categories as $category) {
            $categoryData = [
                'category' => $category,
                'services' => [],
            ];

            foreach ($category->getServices() as $service) {
                $history = $serviceRepository->getHistoryForDays($service, 30);
                $dailyStatus = $serviceRepository->getDailyStatus($service, 30);
                $uptime = $service->computeUptimeRatio($history, 30);

                // Messages actifs
                $messages = $em->getRepository(ServiceMessage::class)->findBy(
                    ['service' => $service, 'isActive' => true],
                    ['createdAt' => 'DESC'],
                );

                // Logs recents (7 derniers jours)
                $logs = $em->createQueryBuilder()
                    ->select('l')
                    ->from('App\Entity\ServiceLog', 'l')
                    ->where('l.service = :service')
                    ->andWhere('l.createdAt >= :since')
                    ->setParameter('service', $service)
                    ->setParameter('since', new \DateTimeImmutable('-7 days'))
                    ->orderBy('l.createdAt', 'DESC')
                    ->getQuery()
                    ->getResult();

                $categoryData['services'][] = [
                    'service' => $service,
                    'uptime' => $uptime,
                    'dailyStatus' => $dailyStatus,
                    'messages' => $messages,
                    'logs' => $logs,
                ];

                // Global status
                if ('down' === $service->getStatus()) {
                    $globalStatus = 'down';
                } elseif ('degraded' === $service->getStatus() && 'down' !== $globalStatus) {
                    $globalStatus = 'degraded';
                } elseif ('maintenance' === $service->getStatus() && 'up' === $globalStatus) {
                    $globalStatus = 'maintenance';
                }
            }

            $servicesData[] = $categoryData;
        }

        // Messages globaux actifs
        $globalMessages = $em->getRepository(ServiceMessage::class)->findBy(
            ['isActive' => true],
            ['createdAt' => 'DESC'],
        );

        return $this->render('status/index.html.twig', [
            'servicesData' => $servicesData,
            'globalStatus' => $globalStatus,
            'globalMessages' => $globalMessages,
            'breadcrumbs' => [
                ['name' => 'Accueil', 'url' => '/'],
                ['name' => 'Status des services'],
            ],
        ]);
    }
}
