<?php

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

use CpCreation\VitiCore\SocialNetwork\Repository\SocialNetworkNewRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class HealthCheckController extends AbstractController
{
    private const MAX_DATA_AGE_SECONDS = 86400;

    private $socialNetworkNewRepository;

    public function __construct(
        SocialNetworkNewRepository $socialNetworkNewRepository,
    ){
        $this->socialNetworkNewRepository = $socialNetworkNewRepository;
    }

    /**
     * @Route("/api/health/instagram",name="api_health_instagram")
     * @return JsonResponse
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function checkInstagramHealth(): JsonResponse
    {
        $socialNetwork = $this->socialNetworkNewRepository->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();
        $dateAge = $now->getTimestamp() - $updatedAt->getTimestamp();

        if ($dateAge > 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' => $dateAge,
                ],
                Response::HTTP_SERVICE_UNAVAILABLE
            );
        }

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

}
