<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiSoftDeleteRestoreArchiveLifecycleContractTest extends FullSurfaceE2EContractCase
{
    /** @test */
    public function archive_restore_and_unarchive_routes_are_controlled_and_role_protected(): void
    {
        $routes = $this->apiRoutesContainingAny(['archive', 'restore', 'unarchive', 'recover']);

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

            $adminResponse = $this->requestAs($this->admin, $method, $uri, $this->payloadFor($method, $uri));
            $this->assertControlled($adminResponse, $method, $uri);

            $parentResponse = $this->requestAs($this->parent, $method, $uri, $this->payloadFor($method, $uri));
            $this->assertStatusIn($parentResponse, [401, 403, 404, 405, 409, 419, 422], "$method $uri should not allow parent archive/restore privileges by accident.");
        }
    }

    /** @test */
    public function destructive_soft_delete_style_routes_tolerate_repeated_requests(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['delete', 'destroy', 'archive', 'cancel', 'void', 'remove']), 0, 80);

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

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

            $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->assertControlled($first, $method, $uri);
            $this->assertControlled($second, $method, $uri);
            $this->assertLessThan(500, $second->getStatusCode(), "$method $uri repeated destructive request should be boring, not catastrophic.");
        }
    }
}
