<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiCacheFreshnessAndConditionalRequestContractTest extends FullSurfaceE2EContractCase
{
    public function test_private_authenticated_resources_are_not_publicly_cacheable(): void
    {
        foreach ($this->apiRoutesContainingAny(['profile', 'auth/me', 'dashboard', 'finance', 'messages', 'students', 'parents']) as $route) {
            if ($this->primaryMethod($route) !== 'GET') {
                continue;
            }

            $response = $this->requestAs($this->actorFor($route->uri()), 'GET', $route->uri());
            $this->assertControlled($response, 'GET', $route->uri());

            $cacheControl = strtolower((string) $response->headers->get('Cache-Control'));
            $this->assertFalse(
                str_contains($cacheControl, 'public') && ! str_contains($cacheControl, 'private'),
                "{$route->uri()} should not publicly cache private authenticated data."
            );
        }
    }

    public function test_conditional_headers_do_not_bypass_authorization_or_return_wrong_user_data(): void
    {
        foreach ($this->apiRoutesContainingAny(['profile', 'auth/me', 'dashboard', 'students', 'invoices']) as $route) {
            if ($this->primaryMethod($route) !== 'GET') {
                continue;
            }

            $response = $this->withHeaders([
                'If-None-Match' => '"fake-etag-from-other-user"',
                'If-Modified-Since' => 'Wed, 21 Oct 2015 07:28:00 GMT',
            ])->getJson($this->materializePath($route->uri()));

            $this->assertStatusIn($response, [401, 403, 404, 419], "Conditional unauthenticated request should not bypass {$route->uri()}.");
        }
    }
}
