<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;

class AuthValidatorController extends AbstractController
{
    private JWTTokenManagerInterface $jwtManager;

    public function __construct(JWTTokenManagerInterface $jwtManager)
    {
        $this->jwtManager = $jwtManager;
    }

    #[Route('/validate', name: 'auth_validate', methods: ['POST'])]
    public function validate(Request $request): Response
    {
        $sslClientVerify = $request->headers->get('SSL_CLIENT_VERIFY');
        $clientCertOk = $sslClientVerify === 'SUCCESS';

        $authHeader = $request->headers->get('Authorization');
        $hasValidJwt = $this->validateJwtToken($authHeader);

        if ($clientCertOk || $hasValidJwt) {
            return new Response('Authorized', Response::HTTP_OK);
        }

        return new Response('Unauthorized', Response::HTTP_UNAUTHORIZED);
    }

    private function validateJwtToken(?string $authHeader): bool
    {
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return false;
        }

        $token = substr($authHeader, 7);

        try {
            $payload = $this->jwtManager->parse($token);

            return true;

        } catch (\Exception $e) {
            return false;
        }
    }
}
