<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Tests\Commerce\Catalog\Api\Security;

use CpCreation\VitiCore\Commerce\Catalog\Api\Security\CommerceAuthenticationEntryPoint;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;

final class CommerceAuthenticationEntryPointTest extends TestCase
{
    public function testItReturnsAStatelessBearerChallenge(): void
    {
        $response = new CommerceAuthenticationEntryPoint()->start(Request::create('/api/commerce/v1/products'));

        self::assertSame(Response::HTTP_UNAUTHORIZED, $response->getStatusCode());
        self::assertSame('Bearer', $response->headers->get('WWW-Authenticate'));
        self::assertSame('application/problem+json', $response->headers->get('Content-Type'));
        self::assertJsonStringEqualsJsonString(
            '{"type":"https://httpstatuses.com/401","title":"Authentication required","status":401,"detail":"A valid bearer token is required."}',
            (string) $response->getContent(),
        );
    }

    public function testAuthenticationFailureUsesTheSameBearerChallenge(): void
    {
        $response = new CommerceAuthenticationEntryPoint()->onAuthenticationFailure(
            Request::create('/api/commerce/v1/products'),
            new BadCredentialsException(),
        );

        self::assertSame(Response::HTTP_UNAUTHORIZED, $response->getStatusCode());
        self::assertSame('Bearer', $response->headers->get('WWW-Authenticate'));
        self::assertSame('application/problem+json', $response->headers->get('Content-Type'));
    }
}
