<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site;

use CpCreation\VitiCore\SocialNetwork\Repository\SocialNetworkRepository;
use Doctrine\ORM\NonUniqueResultException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class HealthCheckController extends AbstractController
{
    private const MAX_DATA_AGE_SECONDS = 86400;

    public function __construct(
        private readonly SocialNetworkRepository $socialNetworkRepository,
    ) {
    }

    /**
     * @throws NonUniqueResultException
     */
    #[Route('/api/health/instagram', name: 'api_health_instagram')]
    public function checkInstagramHealth(): JsonResponse
    {
        $socialNetwork = $this->socialNetworkRepository->findByLikeSocial('basic_instagram');

        if (!$socialNetwork) {
            return new JsonResponse(
                [
                    'status' => 'error',
                    'message' => 'Instagram connection not configured. It should be configured in the database.',
                ],
                Response::HTTP_SERVICE_UNAVAILABLE
            );
        }

        $updatedAt = $socialNetwork->getUpdatedAt();
        $now = new \DateTimeImmutable();
        $dataAgeSeconds = $now->getTimestamp() - $updatedAt->getTimestamp();

        if ($dataAgeSeconds > self::MAX_DATA_AGE_SECONDS) {
            return new JsonResponse(
                [
                    'status' => 'error',
                    'message' => \sprintf(
                        'Instagram data no longer valid (last update: %s)',
                        $updatedAt->format('Y-m-d H:i:s')
                    ),
                    'data_age_seconds' => $dataAgeSeconds,
                ],
                Response::HTTP_SERVICE_UNAVAILABLE
            );
        }

        return new JsonResponse(
            [
                'status' => 'ok',
                'message' => 'Instagram connection is healthy',
                'data_age_seconds' => $dataAgeSeconds,
                'last_updated' => $updatedAt->format('Y-m-d H:i:s'),
            ],
            Response::HTTP_OK
        );
    }
}
