<?php

namespace App\Controller\Api;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
use App\Entity\Post;
use App\Utils\Functions;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Class ApiAnnuaireController
 * @Route("/api/annuaire")
 *
 */
class ApiAnnuaireController extends AbstractController
{
    private const JSON_MAP = [
        'ROSNY' => 'annuaire_rosny.json',
        'BRON' => 'annuaire_bron.json',
    ];

    private $kernel;
    private $annuaire_token;

    public function __construct(KernelInterface $kernel, string $annuaire_token)
    {
        $this->kernel = $kernel;
        $this->annuaire_token = $annuaire_token;
    }

    /**
     * annuaire selon site
     * @Route("/json", methods="GET", name="annuaire_json")
     */
    public function jsonAction(Request $request)
    {
        $token = (string) $request->headers->get('X-Annuaire-Token');
        if ($token === '' || !hash_equals($this->annuaire_token, $token)) {
            return new JsonResponse(['error' => 'Unauthorized'], 401);
        }

        // Choix du JSON via header
        $key = (string) $request->headers->get('X-Site', '');
        if (!isset(self::JSON_MAP[$key])) {
            return new JsonResponse(['error' => 'Invalid site'], 400);
        }

        $path = $this->kernel->getProjectDir().'/assets/json/'.self::JSON_MAP[$key];
        if (!is_file($path)) {
            return new JsonResponse(['error' => 'Not found'], 404);
        }

        $raw = file_get_contents($path);
        $data = json_decode($raw ?: '', true);
        if (!is_array($data)) {
            return new JsonResponse(['error' => 'Invalid JSON'], 500);
        }

        return new JsonResponse($data, 200, ['Cache-Control' => 'no-store']);

    }
}