<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiNotificationPreferenceAndOptOutContractTest extends FullSurfaceE2EContractCase
{
    /** @test */
    public function notification_preference_routes_validate_channels_recipients_and_opt_out_flags(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['notification', 'notify', 'preferences', 'email', 'whatsapp', 'sms']), 0, 90);

        $payloads = [
            ['channel' => 'email', 'email' => 'not-an-email', 'message' => 'bad email'],
            ['channel' => 'sms', 'phone' => 'abc123', 'message' => 'bad phone'],
            ['channel' => 'fax-from-1997', 'recipient_id' => $this->parent->id, 'message' => 'unsupported channel'],
            ['opt_out' => true, 'channel' => 'email', 'recipient_id' => $this->parent->id],
            ['unsubscribe' => true, 'token' => str_repeat('x', 512)],
        ];

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            $uri = $route->uri();

            if (! in_array($method, ['POST', 'PUT', 'PATCH'], true)) {
                continue;
            }

            foreach ($payloads as $payload) {
                $response = $this->requestAs($this->actorFor($uri), $method, $uri, $this->payloadFor($method, $uri) + $payload);
                $this->assertControlled($response, $method, $uri);
            }
        }
    }

    /** @test */
    public function low_privilege_users_cannot_broadcast_notifications_to_everyone(): void
    {
        $routes = $this->apiRoutesContainingAny(['broadcast', 'announcement', 'notify', 'notifications']);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            $uri = $route->uri();

            if (! in_array($method, ['POST', 'PUT', 'PATCH'], true)) {
                continue;
            }

            $payload = $this->payloadFor($method, $uri) + [
                'recipients' => 'all',
                'role' => 'administrator',
                'message' => 'Parent should not broadcast to everyone.',
            ];

            $response = $this->requestAs($this->parent, $method, $uri, $payload);
            $this->assertStatusIn($response, [401, 403, 404, 405, 409, 419, 422], "$method $uri should not let low-privilege users broadcast globally.");
        }
    }
}
