<?php

namespace Tests\Feature\Api\V1\FullSurface;

use Illuminate\Http\UploadedFile;
use Tests\Feature\Api\V1\FullSurface\Support\FullSurfaceE2EContractCase;

class ApiFileMediaMetadataSafetyContractTest extends FullSurfaceE2EContractCase
{
    /** @test */
    public function upload_routes_reject_misleading_metadata_and_path_names_cleanly(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['upload', 'import', 'document', 'attachment', 'file', 'photo', 'avatar']), 0, 80);

        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) + [
                'file' => UploadedFile::fake()->create('../evil.php', 12, 'application/x-php'),
                'filename' => '../storage/logs/laravel.log',
                'original_name' => "invoice\0.pdf",
                'mime_type' => 'image/png; charset=utf-8',
            ];

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

            $this->assertControlled($response, $method, $uri);
            $this->assertLessThan(500, $response->getStatusCode(), "$method $uri should handle misleading upload metadata without server errors.");
        }
    }

    /** @test */
    public function download_routes_do_not_accept_path_traversal_identifiers(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['download', 'export', 'file', 'attachment', 'receipt', 'certificate']), 0, 90);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            $uri = $route->uri();
            $payload = $this->payloadFor($method, $uri) + [
                'filename' => '../../.env',
                'path' => '../../storage/logs/laravel.log',
                'file' => '../../composer.json',
            ];

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

            $this->assertControlled($response, $method, $uri);
            $this->assertStringNotContainsString('APP_KEY=', $response->getContent(), "$method $uri must not leak environment files.");
        }
    }
}
