<?php

namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Mailer\MailerInterface;

class CspReportControllerTest extends WebTestCase
{
    public function testInvalidPayloadReturnsBadRequest(): void
    {
        $client = static::createClient();
        $client->request('POST', '/my-csp-report', [], [], [
            'CONTENT_TYPE' => 'application/json',
        ], '');

        self::assertResponseStatusCodeSame(400);
    }

    public function testBrowserExtensionViolationIsIgnored(): void
    {
        $client = static::createClient();
        $payload = json_encode([
            'csp-report' => [
                'source-file' => 'chrome-extension://abc',
                'blocked-uri' => 'inline',
                'document-uri' => 'https://e-cosplay.fr/',
                'violated-directive' => 'script-src',
            ],
        ]);

        $client->request('POST', '/my-csp-report', [], [], [
            'CONTENT_TYPE' => 'application/json',
        ], $payload);

        self::assertResponseStatusCodeSame(204);
    }

    public function testRealViolationIsProcessed(): void
    {
        $client = static::createClient();
        $payload = json_encode([
            'csp-report' => [
                'source-file' => 'https://evil.com/script.js',
                'blocked-uri' => 'https://evil.com',
                'document-uri' => 'https://e-cosplay.fr/page',
                'violated-directive' => 'script-src',
            ],
        ]);

        $client->request('POST', '/my-csp-report', [], [], [
            'CONTENT_TYPE' => 'application/json',
        ], $payload);

        self::assertResponseStatusCodeSame(204);
    }

    public function testRealViolationHandlesMailerFailure(): void
    {
        $client = static::createClient();

        $mailer = $this->createMock(MailerInterface::class);
        $mailer->method('send')->willThrowException(new \RuntimeException('SMTP down'));
        static::getContainer()->set(MailerInterface::class, $mailer);

        $payload = json_encode([
            'csp-report' => [
                'source-file' => 'https://evil.com/script.js',
                'blocked-uri' => 'https://evil.com',
                'document-uri' => 'https://e-cosplay.fr/page',
                'violated-directive' => 'script-src',
            ],
        ]);

        $client->request('POST', '/my-csp-report', [], [], [
            'CONTENT_TYPE' => 'application/json',
        ], $payload);

        self::assertResponseStatusCodeSame(204);
    }

    public function testGetRequestReturns204(): void
    {
        $client = static::createClient();
        $client->request('GET', '/my-csp-report');

        self::assertResponseStatusCodeSame(204);
    }
}
