<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

use Illuminate\Http\UploadedFile;

class ApiBatch12AttachmentLifecycleContractTest extends FullSurfaceE2EContractCase
{
    public function test_attachment_upload_routes_handle_multiple_file_shapes_cleanly(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['upload', 'attachment', 'document', 'import', 'media', 'file']), 0, 120);
        $files = [
            UploadedFile::fake()->create('normal.pdf', 12, 'application/pdf'),
            UploadedFile::fake()->create('image-as-pdf.pdf', 12, 'image/png'),
            UploadedFile::fake()->create('script.php', 1, 'application/x-php'),
        ];

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

            foreach ($files as $file) {
                $response = $this->requestAs($this->actorFor($route->uri()), $method, $route->uri(), $this->payloadFor($method, $route->uri()) + [
                    'file' => $file,
                    'attachment' => $file,
                    'document' => $file,
                ]);

                $this->assertControlled($response, $method, $route->uri());
                $this->assertNoServerError($response, 'attachment lifecycle '.$method.' '.$route->uri());
            }
        }
    }

    public function test_file_download_routes_reject_path_and_storage_driver_probing(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['download', 'file', 'media', 'receipt', 'certificate', 'badge']), 0, 100);

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            $response = $this->requestAs($this->actorFor($route->uri()), $method, $route->uri(), [
                'path' => '../../.env',
                'disk' => 's3',
                'filename' => '../storage/logs/laravel.log',
            ]);

            $this->assertControlled($response, $method, $route->uri());
            $this->assertNoServerError($response, 'file path probe '.$method.' '.$route->uri());
            $this->assertStringNotContainsString('APP_KEY', $response->getContent(), 'download route exposed environment content');
        }
    }
}
