<?php

namespace App\Controller\Api;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

trait ApiAuthTrait
{
    private function authenticateRequest(Request $request, EntityManagerInterface $em, string $appSecret): User|JsonResponse
    {
        $email = $request->headers->get('ETicket-Email', '');
        $jwt = $request->headers->get('ETicket-JWT', '');
        $result = ('' !== $email && '' !== $jwt) ? ApiAuthController::verifyJwt($jwt, $email, $appSecret) : ['userId' => null, 'expired' => false];

        if (null === $result['userId'] || $result['expired']) {
            $error = null === $result['userId'] ? 'Token invalide ou headers manquants.' : 'Token expire. Utilisez POST /api/auth/refresh.';

            return new JsonResponse(['success' => false, 'data' => null, 'error' => $error], 401);
        }

        $user = $em->getRepository(User::class)->find($result['userId']);

        return $user && $user->getEmail() === $email
            ? $user
            : new JsonResponse(['success' => false, 'data' => null, 'error' => 'Utilisateur introuvable.'], 401);
    }

    /** @param array<string, mixed> $meta */
    private function success(mixed $data, array $meta = []): JsonResponse
    {
        $response = ['success' => true, 'data' => $data, 'error' => null];
        if ([] !== $meta) {
            $response['meta'] = $meta;
        }

        return new JsonResponse($response);
    }

    private function error(string $message, int $status = 400): JsonResponse
    {
        return new JsonResponse(['success' => false, 'data' => null, 'error' => $message], $status);
    }
}
