<?php

namespace Tests\Feature\Api\V1\FullSurface;

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

class ApiImportTemplateAndCsvContractTest extends FullSurfaceE2EContractCase
{
    public function test_import_routes_reject_malformed_csv_rows_without_server_errors(): void
    {
        $routes = $this->apiRoutesContainingAny(['import', 'upload', 'csv', 'bulk']);
        $file = UploadedFile::fake()->createWithContent('malformed.csv', "name,email,amount\n\"unterminated,row\n<script>,bad-email,not-money\n");

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

            $uri = $route->uri();
            $response = $this->actingAs($this->actorFor($uri), 'api')->json($method, $this->materializePath($uri), $this->payloadFor($method, $uri) + ['file' => $file]);

            $this->assertControlled($response, $method, $uri);
            $this->assertNoServerError($response, 'malformed csv import at ' . $method . ' ' . $uri);
        }
    }

    public function test_template_download_routes_are_not_public_when_templates_include_private_columns(): void
    {
        $routes = $this->apiRoutesContainingAny(['template', 'download', 'export']);

        foreach (array_slice($routes, 0, 100) as $route) {
            if ($this->primaryMethod($route) !== 'GET') {
                continue;
            }

            $uri = $route->uri();
            $public = $this->getJson($this->materializePath($uri));
            $authenticated = $this->actingAs($this->actorFor($uri), 'api')->getJson($this->materializePath($uri));

            $this->assertStatusIn($public, [200, 204, 302, 400, 401, 403, 404, 405, 419, 422], 'public template download ' . $uri);
            $this->assertControlled($authenticated, 'GET', $uri);
            $this->assertNoServerError($authenticated, 'authenticated template download ' . $uri);
        }
    }
}
