<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiBatch13MobileOfflineSyncConflictContractTest extends FullSurfaceE2EContractCase
{
    public function test_offline_sync_headers_do_not_override_authorization_or_state(): void
    {
        $routes = $this->apiRoutesContainingAny(['attendance', 'scores', 'homework', 'message', 'payment', 'profile']);

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

            $this->withHeaders([
                'X-Client-Version' => '0.0.1-offline',
                'X-Device-Id' => '../shared-device',
                'X-Offline-Sequence' => '-999',
                'X-Last-Synced-At' => '1900-01-01T00:00:00Z',
                'Idempotency-Key' => 'batch13-offline-sync-conflict',
            ]);

            $response = $this->requestAs($this->actorFor($route->uri()), $method, $route->uri(), $this->payloadFor($method, $route->uri()) + [
                'client_updated_at' => '1900-01-01T00:00:00Z',
                'server_version' => -1,
                'force_sync' => true,
                'resolve_conflict' => 'client_wins',
            ]);

            $this->assertControlled($response, $method, $route->uri());
            $this->assertNotContains($response->getStatusCode(), [500, 501, 502, 503]);
        }
    }

    public function test_duplicate_offline_submissions_have_controlled_outcome(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['attendance', 'scores', 'message']), 0, 20);

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

            $payload = $this->payloadFor($method, $route->uri()) + ['offline_uuid' => 'BATCH13-OFFLINE-DUPLICATE'];
            $first = $this->requestAs($this->actorFor($route->uri()), $method, $route->uri(), $payload);
            $second = $this->requestAs($this->actorFor($route->uri()), $method, $route->uri(), $payload);

            $this->assertControlled($first, $method, $route->uri());
            $this->assertControlled($second, $method, $route->uri());
        }
    }
}
