<?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
    {
        $row = $this->connection->fetchAssociative(
            'SELECT detected_at, source, coverage_area
             FROM sargassum_observation
             ORDER BY detected_at DESC LIMIT 1'
        );

        return $this->json([
            'lastObservation' => $row !== false ? [
                'detectedAt'   => $row['detected_at'],
                'source'       => $row['source'],
                'coverageKm2'  => $row['coverage_area'] !== null ? (float) $row['coverage_area'] : null,
            ] : null,
        ]);
    }
}
