<?php

namespace App\Controller\Api\V1;

use App\Entity\ApiKey;
use App\Entity\User;
use App\Repository\ApiKeyRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

final class ApiKeyController extends AbstractController
{
    #[Route('/api-keys', name: 'api_keys_list', methods: ['GET'])]
    #[IsGranted('ROLE_USER')]
    public function listApiKeys(ApiKeyRepository $apiKeyRepository): JsonResponse
    {
        $user = $this->getUser();

        // Les admins voient toutes les clés, les autres ne voient que les leurs
        if ($this->isGranted('ROLE_ADMIN')) {
            $keys = $apiKeyRepository->findAll();
        } else {
            $keys = $apiKeyRepository->findByUser($user);
        }

        $data = array_map(function (ApiKey $key) {
            return [
                'id' => $key->getId(),
                'name' => $key->getName(),
                'owner' => $key->getUser()->getPseudo(),
                'token' => substr($key->getToken(), 0, 10) . '...', // Masquer le token complet
                'createdAt' => $key->getCreatedAt()?->format('c'),
                'lastUsedAt' => $key->getLastUsedAt()?->format('c'),
                'expiresAt' => $key->getExpiresAt()?->format('c'),
                'isActive' => $key->isActive(),
            ];
        }, $keys);

        return $this->json([
            'apiKeys' => $data,
        ]);
    }

    #[Route('/api-keys', name: 'api_keys_create', methods: ['POST'])]
    #[IsGranted('ROLE_USER')]
    public function createApiKey(
        Request $request,
        EntityManagerInterface $entityManager
    ): JsonResponse {
        $data = json_decode($request->getContent(), true);

        if (!isset($data['name'])) {
            return $this->json(['error' => 'name is required'], Response::HTTP_BAD_REQUEST);
        }

        // Les admins peuvent créer des clés pour d'autres utilisateurs
        $currentUser = $this->getUser();
        if ($this->isGranted('ROLE_ADMIN') && isset($data['userId'])) {
            // Un admin veut créer une clé pour un autre utilisateur
            // Cette logique dépend de votre implémentation
            $user = $entityManager->getRepository(User::class)->find($data['userId']);
            if (!$user) {
                return $this->json(['error' => 'User not found'], Response::HTTP_NOT_FOUND);
            }
        } else {
            $user = $currentUser;
        }

        $apiKey = new ApiKey();
        $apiKey->setName($data['name']);
        $apiKey->setUser($user);

        if (isset($data['expiresAt'])) {
            $apiKey->setExpiresAt(new \DateTime($data['expiresAt']));
        }

        $entityManager->persist($apiKey);
        $entityManager->flush();

        return $this->json([
            'id' => $apiKey->getId(),
            'name' => $apiKey->getName(),
            'token' => $apiKey->getToken(),
            'createdAt' => $apiKey->getCreatedAt()?->format('c'),
            'message' => 'Copier le token en lieu sûr',
        ], Response::HTTP_CREATED);
    }

    #[Route('/api-keys/{id}', name: 'api_keys_get', methods: ['GET'])]
    #[IsGranted('ROLE_USER')]
    public function getApiKey(
        ApiKey $apiKey,
        EntityManagerInterface $entityManager
    ): JsonResponse {
        $user = $this->getUser();

        // Seuls les propriétaires peuvent voir les détails d'une clé
        if ($apiKey->getUser() !== $user) {
            return $this->json(['error' => 'Unauthorized'], Response::HTTP_FORBIDDEN);
        }

        return $this->json([
            'id' => $apiKey->getId(),
            'name' => $apiKey->getName(),
            'token' => $apiKey->getToken(),
            'createdAt' => $apiKey->getCreatedAt()?->format('c'),
            'lastUsedAt' => $apiKey->getLastUsedAt()?->format('c'),
            'expiresAt' => $apiKey->getExpiresAt()?->format('c'),
            'isActive' => $apiKey->isActive(),
            'message' => 'Copier le token en lieu sûr',
        ]);
    }

    #[Route('/api-keys/{id}', name: 'api_keys_delete', methods: ['DELETE'])]
    #[IsGranted('ROLE_USER')]
    public function deleteApiKey(
        ApiKey $apiKey,
        EntityManagerInterface $entityManager
    ): JsonResponse {
        $user = $this->getUser();

        // Les admins peuvent supprimer n'importe quelle clé, les autres seulement les leurs
        if (!$this->isGranted('ROLE_ADMIN') && $apiKey->getUser() !== $user) {
            return $this->json(['error' => 'Unauthorized'], Response::HTTP_FORBIDDEN);
        }

        $entityManager->remove($apiKey);
        $entityManager->flush();

        return $this->json(['message' => 'API key deleted']);
    }

    #[Route('/api-keys/{id}/deactivate', name: 'api_keys_deactivate', methods: ['PATCH'])]
    #[IsGranted('ROLE_USER')]
    public function deactivateApiKey(
        ApiKey $apiKey,
        EntityManagerInterface $entityManager
    ): JsonResponse {
        $user = $this->getUser();

        // Les admins peuvent désactiver n'importe quelle clé, les autres seulement les leurs
        if (!$this->isGranted('ROLE_ADMIN') && $apiKey->getUser() !== $user) {
            return $this->json(['error' => 'Unauthorized'], Response::HTTP_FORBIDDEN);
        }

        $apiKey->setIsActive(false);
        $entityManager->flush();

        return $this->json(['message' => 'API key deactivated']);
    }
}
