<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiNotificationMessagingDeliveryContractTest extends FullSurfaceE2EContractCase
{
    public function test_message_notification_and_broadcast_routes_validate_recipients_and_channels(): void
    {
        $routes = $this->apiRoutesContainingAny(['messages', 'notifications', 'broadcast', 'email', 'whatsapp', 'communication']);

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

            $uri = $route->uri();
            $payload = $this->payloadFor($method, $uri) + [
                'recipient_id' => 999999,
                'recipients' => [999999, $this->parent->id, 'not-an-id'],
                'channel' => 'carrier-pigeon',
                'email' => 'not-an-email',
                'phone' => '../../../etc/passwd',
                'subject' => str_repeat('Subject ', 100),
                'message' => str_repeat('Body ', 500),
            ];

            $response = $this->requestAs($this->actorFor($uri), $method, $uri, $payload);
            $this->assertNoServerError($response, "$method $uri bad delivery inputs");
            $this->assertControlled($response, $method, $uri);
            $this->assertStringNotContainsStringIgnoringCase('Swift', $response->getContent(), $uri . ' should not leak mail transport internals.');
            $this->assertStringNotContainsStringIgnoringCase('SMTP', $response->getContent(), $uri . ' should not leak SMTP internals.');
        }
    }

    public function test_read_archive_star_and_delete_message_actions_are_idempotent(): void
    {
        $routes = $this->apiRoutesContainingAny(['messages', 'inbox', 'archive', 'read', 'star']);

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

            $uri = $route->uri();
            $first = $this->requestAs($this->actorFor($uri), $method, $uri, $this->payloadFor($method, $uri));
            $second = $this->requestAs($this->actorFor($uri), $method, $uri, $this->payloadFor($method, $uri));

            $this->assertNoServerError($first, "$method $uri first message action");
            $this->assertNoServerError($second, "$method $uri repeated message action");
            $this->assertControlled($first, $method, $uri);
            $this->assertControlled($second, $method, $uri);
        }
    }
}
