<?php

namespace App\Controller;

use Doctrine\DBAL\Connection;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;

/**
 * GET /api/status — fraîcheur des données pour l'indicateur UI
 */
#[Route('/api/status', name: 'api_status', methods: ['GET'])]
class StatusController extends AbstractController
{
    public function __construct(private Connection $connection) {}

    public function __invoke(): JsonResponse
    {
        $obs = $this->connection->fetchAssociative(
            'SELECT detected_at, source, coverage_area
             FROM sargassum_observation
             ORDER BY detected_at DESC LIMIT 1'
        );

        $job = $this->connection->fetchAssociative(
            "SELECT status, source, error_message, requested_at, processed_at, retry_count
             FROM data_ingestion_job
             ORDER BY requested_at DESC LIMIT 1"
        );

        // Healthcheck : données fraîches si dernière observation < 6h
        $healthy = false;
        $alertReason = null;

        if ($obs !== false && $obs['detected_at'] !== null) {
            $detectedAt = new \DateTimeImmutable($obs['detected_at'], new \DateTimeZone('UTC'));
            $now        = new \DateTimeImmutable('now', new \DateTimeZone('UTC'));
            $ageSeconds = $now->getTimestamp() - $detectedAt->getTimestamp();

            if ($ageSeconds <= 6 * 3600) {
                $healthy = true;
            } else {
                $alertReason = 'stale_data';
            }
        } else {
            $alertReason = 'no_data';
        }

        return $this->json([
            'healthy'     => $healthy,
            'alertReason' => $alertReason,
            'lastObservation' => $obs !== false ? [
                'detectedAt'  => $obs['detected_at'],
                'source'      => $obs['source'],
                'coverageKm2' => $obs['coverage_area'] !== null ? (float) $obs['coverage_area'] : null,
            ] : null,
            'lastIngestionJob' => $job !== false ? [
                'status'      => $job['status'],
                'source'      => $job['source'],
                'error'       => $job['error_message'],
                'startedAt'   => $job['requested_at'],
                'finishedAt'  => $job['processed_at'],
                'retryCount'  => (int) $job['retry_count'],
            ] : null,
        ]);
    }
}
