<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiQueueJobAndAsyncTriggerContractTest extends FullSurfaceE2EContractCase
{
    public function test_async_trigger_routes_are_admin_or_owner_scoped_and_fail_cleanly(): void
    {
        $routes = $this->apiRoutesContainingAny(['send', 'dispatch', 'queue', 'job', 'broadcast', 'notify', 'reminder', 'sync', 'import', 'export']);

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

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

            $studentAttempt = $this->requestAs($this->studentUser, $method, $uri, $this->payloadFor($method, $uri));
            $this->assertStatusIn($studentAttempt, [400, 401, 403, 404, 405, 409, 419, 422], 'student async trigger ' . $method . ' ' . $uri);
            $this->assertNoServerError($studentAttempt, 'student async trigger ' . $method . ' ' . $uri);

            $adminAttempt = $this->requestAs($this->admin, $method, $uri, $this->payloadFor($method, $uri));
            $this->assertControlled($adminAttempt, $method, $uri);
            $this->assertNoServerError($adminAttempt, 'admin async trigger ' . $method . ' ' . $uri);
        }
    }

    public function test_async_triggers_tolerate_duplicate_client_request_ids(): void
    {
        $routes = $this->apiRoutesContainingAny(['send', 'dispatch', 'notify', 'broadcast', 'reminder']);

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

            $uri = $route->uri();
            $payload = $this->payloadFor($method, $uri) + ['client_request_id' => 'e2e-duplicate-async-trigger'];

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

            $this->assertControlled($first, $method, $uri);
            $this->assertControlled($second, $method, $uri);
            $this->assertNoServerError($second, 'duplicate async trigger ' . $method . ' ' . $uri);
        }
    }
}
