<?php

namespace App\Controller\Api\V1;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

final class StateController extends AbstractController
{
    #[Route('/health', name: 'app_api_v1_health', methods: ['GET'])]
    public function health(): JsonResponse
    {
        return $this->json([
            'status' => 'ok',
            'timestamp' => date('c'),
        ]);
    }

    #[Route('/profile', name: 'app_api_v1_profile', methods: ['GET'])]
    #[IsGranted('ROLE_USER')]
    public function profile(): JsonResponse
    {
        $user = $this->getUser();

        return $this->json([
            'id' => $user->getId(),
            'pseudo' => $user->getPseudo(),
            'roles' => $user->getRoles(),
            'authenticatedVia' => $this->getAuthenticationMode(),
        ]);
    }

    /**
     * Déterminer le mode d'authentification utilisé
     */
    private function getAuthenticationMode(): string
    {
        $token = $this->container->get('security.token_storage')->getToken();

        if (!$token) {
            return 'none';
        }

        $tokenClass = basename(str_replace('\\', '/', $token::class));

        if (strpos($tokenClass, 'AccessToken') !== false) {
            return 'api_key';
        }

        return 'session';
    }
}
