<?php

app_require('classes/attachment_store.php');

use classes\attachment_store;
use classes\pdf_store;

it('registers authenticated attachment streaming with ownership and safe headers', function (): void {
    $content = file_get_contents(app_path('routes/ordersRoute.php'));
    expect($content)->not->toBeFalse();
    $content = (string)$content;

    expect($content)->toContain("\$this->get('/orders/attachments/content'");
    expect($content)->toContain('(int)$attachment->object_id->value() !== $orderId');
    expect($content)->toContain("\$attachmentType !== 'orders'");
    expect($content)->toContain('$formattedAttachment->content->document');
    expect($content)->toContain('$formattedAttachment->content->image');
    expect($content)->toContain('$formattedAttachment->isWashCertificate()');
    expect($content)->toContain('$isWashCertificate ? new pdf_store() : $attachmentStore');
    expect($content)->toContain("header('Content-Disposition: '");
    expect($content)->toContain("header('Cache-Control: private, no-store')");
    expect($content)->toContain("header('X-Content-Type-Options: nosniff')");
});

it('keeps the legacy link HTTPS and safely encodes attachment object paths', function (): void {
    $store = new attachment_store();

    expect($store->generateDirectDownloadUrl('folder/test_file.pdf'))
        ->toBe('https://api.truckwash.io/files/folder/test_file.pdf');
    expect(fn() => $store->generateDirectDownloadUrl('../secret.pdf'))
        ->toThrow(InvalidArgumentException::class);
});

it('downloads uploaded attachments and generated wash certificates through isolated temporary files', function (): void {
    $previousRunApiTests = getenv('RUN_API_TESTS');
    $previousMinio = $GLOBALS['MINIO'] ?? null;
    putenv('RUN_API_TESTS=1');
    $GLOBALS['MINIO'] = ['endpoint' => '', 'access_key' => '', 'secret_key' => ''];

    $attachmentStore = new attachment_store();
    $pdfStore = new pdf_store();
    $attachmentKey = 'unit/' . uniqid('attachment_', true) . '.txt';
    $certificateKey = 'pdf_' . uniqid('wash_certificate_', true) . '.pdf';
    $attachmentTemporaryPath = null;
    $certificateTemporaryPath = null;

    try {
        expect($attachmentStore->createObject($attachmentKey, 'attachment-content'))->toBeTrue();
        expect($pdfStore->createObject($certificateKey, '%PDF-1.4 wash certificate'))->toBeTrue();
        expect($attachmentStore->doesObjectExist($certificateKey))->toBeFalse();
        expect($pdfStore->doesObjectExist($certificateKey))->toBeTrue();

        $attachmentTemporaryPath = $attachmentStore->downloadToTemporaryFile($attachmentKey);
        $certificateTemporaryPath = $pdfStore->downloadToTemporaryFile($certificateKey);

        expect($attachmentTemporaryPath)->toBeFile();
        expect(file_get_contents($attachmentTemporaryPath))->toBe('attachment-content');
        expect($certificateTemporaryPath)->toBeFile();
        expect(file_get_contents($certificateTemporaryPath))->toBe('%PDF-1.4 wash certificate');
        expect(basename($attachmentTemporaryPath))->toStartWith('stored_object_');
        expect(basename($certificateTemporaryPath))->toStartWith('stored_object_');
    } finally {
        foreach ([$attachmentTemporaryPath, $certificateTemporaryPath] as $temporaryPath) {
            if (is_string($temporaryPath) && file_exists($temporaryPath)) {
                unlink($temporaryPath);
            }
        }
        if ($previousRunApiTests === false) {
            putenv('RUN_API_TESTS');
        } else {
            putenv('RUN_API_TESTS=' . $previousRunApiTests);
        }
        if ($previousMinio === null) {
            unset($GLOBALS['MINIO']);
        } else {
            $GLOBALS['MINIO'] = $previousMinio;
        }
    }
});
