<?php

namespace Tests\Unit\Services\Files;

use App\Services\Files\FileServeService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\TestCase;

class FileServeServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_meta_returns_file_metadata(): void
    {
        $dir = storage_path('testing/files');
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        $path = $dir . DIRECTORY_SEPARATOR . 'sample.pdf';
        file_put_contents($path, 'PDFDATA');

        $service = new FileServeService();
        $meta = $service->meta($dir, 'sample.pdf', ['pdf'], 'download');

        $this->assertSame('sample.pdf', $meta['name']);
        $this->assertSame('download.pdf', $meta['download_name']);
        $this->assertSame(7, $meta['size']);
        $this->assertNotEmpty($meta['etag']);
    }

    public function test_serve_inline_returns_304_when_etag_matches(): void
    {
        $dir = storage_path('testing/files');
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        $path = $dir . DIRECTORY_SEPARATOR . 'cached.pdf';
        file_put_contents($path, 'PDFDATA');

        $service = new FileServeService();
        $meta = $service->meta($dir, 'cached.pdf', ['pdf']);

        $request = Request::create('/files/cached.pdf', 'GET', [], [], [], [
            'HTTP_IF_NONE_MATCH' => $meta['etag'],
        ]);

        $response = $service->serveInline($dir, 'cached.pdf', ['pdf'], $request);

        $this->assertSame(304, $response->getStatusCode());
        $this->assertSame($meta['etag'], $response->headers->get('ETag'));
    }

    public function test_serve_inline_rejects_invalid_extension(): void
    {
        $this->expectException(HttpException::class);

        $dir = storage_path('testing/files');
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        $path = $dir . DIRECTORY_SEPARATOR . 'sample.exe';
        file_put_contents($path, 'DATA');

        $service = new FileServeService();
        $service->meta($dir, 'sample.exe', ['pdf']);
    }
}
