<?php

namespace Tests\Feature\Api\V1\FullSurface;

use Tests\Feature\Api\V1\FullSurface\Support\FullSurfaceE2EContractCase;

class ApiBatch13ContactMessagingAbuseModerationContractTest extends FullSurfaceE2EContractCase
{
    public function test_message_and_contact_routes_handle_spam_headers_and_html_payloads(): void
    {
        $routes = $this->apiRoutesContainingAny(['message', 'contact', 'support', 'communication', 'broadcast', 'email', 'whatsapp']);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            if (! in_array($method, ['POST', 'PUT', 'PATCH'], true)) {
                continue;
            }

            $payload = $this->payloadFor($method, $route->uri()) + [
                'subject' => "Batch 13\r\nBcc: victim@example.test",
                'message' => '<img src=x onerror=alert(1)>'.str_repeat('spam ', 2000),
                'body' => '<script>alert("batch13")</script>',
                'from' => 'attacker@example.test\r\nCc: injected@example.test',
                'recipients' => array_fill(0, 500, 'victim@example.test'),
                'channel' => 'all',
            ];

            $response = $this->requestAs($this->parent, $method, $route->uri(), $payload);
            $this->assertControlled($response, $method, $route->uri());
            $this->assertStringNotContainsString('Bcc: victim@example.test', $response->getContent());
            $this->assertStringNotContainsString('<script>alert("batch13")</script>', $response->getContent());
        }
    }

    public function test_broadcast_routes_remain_admin_only_under_channel_spoofing(): void
    {
        $routes = $this->apiRoutesContainingAny(['broadcast', 'email', 'notification', 'whatsapp']);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            if (! in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'], true)) {
                continue;
            }

            $response = $this->requestAs($this->teacher, $method, $route->uri(), [
                'recipients' => ['all'],
                'audience' => 'all_school',
                'channel' => 'admin',
                'force' => true,
            ]);

            $this->assertControlled($response, $method, $route->uri());
            $this->assertNotContains($response->getStatusCode(), [200, 201]);
        }
    }
}
