<?php

namespace App\Tests\Security;

use App\Security\AccessDeniedHandler;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Twig\Environment;

#[AllowMockObjectsWithoutExpectations]
class AccessDeniedHandlerTest extends TestCase
{
    private $urlGenerator;
    private $twig;
    private $handler;

    protected function setUp(): void
    {
        $this->urlGenerator = $this->createMock(UrlGeneratorInterface::class);
        $this->twig = $this->createMock(Environment::class);
        $this->handler = new AccessDeniedHandler($this->urlGenerator, $this->twig);
    }

    public function testHandleAdminPathRedirectsToHome()
    {
        $request = Request::create('/admin/dashboard');
        $exception = new AccessDeniedException();

        $this->urlGenerator->expects($this->once())
            ->method('generate')
            ->with('app_home')
            ->willReturn('/home');

        $response = $this->handler->handle($request, $exception);

        $this->assertInstanceOf(RedirectResponse::class, $response);
        $this->assertEquals('/home', $response->getTargetUrl());
    }

    public function testHandleJsonRequestReturnsForbidden()
    {
        $request = Request::create('/api/data');
        $request->headers->set('Accept', 'application/json');
        $exception = new AccessDeniedException();

        $response = $this->handler->handle($request, $exception);

        $this->assertInstanceOf(JsonResponse::class, $response);
        $this->assertEquals(Response::HTTP_FORBIDDEN, $response->getStatusCode());
    }

    public function testHandleDefaultReturnsForbidden()
    {
        $request = Request::create('/some/other/path');
        $exception = new AccessDeniedException();

        $response = $this->handler->handle($request, $exception);

        $this->assertInstanceOf(JsonResponse::class, $response);
        $this->assertEquals(Response::HTTP_FORBIDDEN, $response->getStatusCode());
    }
}
