<?php

namespace App\Controller;

use App\Entity\Account;
use App\Entity\AccountResetPasswordRequest;
use App\Form\RequestPasswordConfirmType;
use App\Form\RequestPasswordRequestType;
use App\Service\ResetPassword\Event\ResetPasswordConfirmEvent;
use App\Service\ResetPassword\Event\ResetPasswordEvent;
use Doctrine\ORM\EntityManagerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Twig\Environment;

class HomeController extends AbstractController
{

    #[Route(path: '/', name: 'app_home', options: ['sitemap' => false], methods: ['GET'])]
    public function index(): Response
    {
        return $this->render('home.twig');
    }

    #[Route('/present-a-{city}',name: 'app_who',options: ['sitemap' => false], methods: ['GET'])]
    public function present(?string $city): Response
    {

        if(is_null($city)){
            return $this->redirectToRoute('app_home');
        }

        return $this->render('who.twig',[
            'city' => $city,
        ]);
    }
    #[Route('/present-a-02-{city}',name: 'app_who_2',options: ['sitemap' => false], methods: ['GET'],priority: 5)]
    public function presentDepartement(?string $city): Response
    {

        if(is_null($city)){
            return $this->redirectToRoute('app_home');
        }

        return $this->render('who.twig',[
            'city' => $city,
        ]);
    }
    const SENTRY_HOST = 'sentry.esy-web.dev';
    const SENTRY_PROJECT_IDS = ['7'];

    #[Route('/uptime',name: 'app_uptime',options: ['sitemap' => false], methods: ['GET'])]
    public function app_uptime(Request $request,HttpClientInterface $httpClient): Response
    {
        return $this->json([]);
    }

    #[Route('/tunnel',name: 'app_tunnel',options: ['sitemap' => false], methods: ['POST'])]
    public function tunnel(Request $request,HttpClientInterface $httpClient): Response
    {
        $envelope = $request->getContent();
        if (empty($envelope)) {
            return $this->json([]);
        }

        try {
            // 2. Extract the header piece (first line)
            $pieces = explode("\n", $envelope, 2);
            $piece = $pieces[0];

            // 3. Parse the header (which is JSON)
            $header = json_decode($piece, true);

            if (!isset($header['dsn'])) {
                throw new \Exception("Missing DSN in envelope header.");
            }

            // 4. Extract and validate DSN and Project ID
            $dsnUrl = parse_url($header['dsn']);
            $dsnHostname = $dsnUrl['host'] ?? null;
            $dsnPath = $dsnUrl['path'] ?? '/';

            // Remove leading/trailing slashes from the path to get the project_id
            $projectId = trim($dsnPath, '/');


            if ($dsnHostname !== self::SENTRY_HOST) {
                throw new \Exception("Invalid sentry hostname: {$dsnHostname}");
            }

            if (empty($projectId) || !in_array($projectId, self::SENTRY_PROJECT_IDS)) {
                throw new \Exception("Invalid sentry project id: {$projectId}");
            }

            // 5. Construct the upstream Sentry URL
            $upstreamSentryUrl = "https://" . self::SENTRY_HOST . "/api/" . $projectId . "/envelope/";

            // 6. Forward the request using an HTTP client (e.g., Guzzle)

            $response = $httpClient->request("POST",$upstreamSentryUrl, [
                'body' => $envelope,
                'headers' => [
                    // Sentry expects this content type
                    'Content-Type' => 'application/x-sentry-envelope',
                    // Forward the content encoding if present, though often not needed
                    // 'Content-Encoding' => $request->headers->get('Content-Encoding'),
                ],
            ]);

            // 7. Return the status from the upstream Sentry response
            return new JsonResponse([], $response->getStatusCode());

        } catch (\Exception $e) {
            // Log the error for server-side debugging
            error_log("Error tunneling to Sentry: " . $e->getMessage());

            // Return a success status (200/202) or a non-specific 500 to the client.
            // Returning a non-error status (like 200) is often preferred for tunnels
            // to avoid triggering ad-blockers on failures.
            return new JsonResponse([
                'error' => 'An error occurred during tunneling.'
            ], JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
}
