<?php

use App\Models\Import;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

it('downloads the original import file', function () {
    // Create a test file
    $uuid = (string) Str::uuid();
    $disk = 'local';
    $path = "imports/{$uuid}.csv";
    $csv = "email,reference\nalpha@example.com,REF-1\n";
    Storage::disk($disk)->put($path, $csv);

    // Authenticate a user
    $user = User::factory()->create();
    Auth::login($user);

    // Create import record
    $import = Import::create([
        'uuid' => $uuid,
        'user_id' => $user->id,
        'import_template_id' => null,
        'client_id' => null,
        'source_type' => 'csv',
        'file_name' => basename($path),
        'original_name' => 'test-import.csv',
        'disk' => $disk,
        'path' => $path,
        'size' => strlen($csv),
        'status' => 'uploaded',
        'meta' => ['has_header' => true],
    ]);

    // Test download endpoint
    $response = test()->get(route('imports.download', ['import' => $import->id]));

    $response->assertSuccessful();
    expect($response->headers->get('Content-Disposition'))->toContain('test-import.csv');
    
    // Clean up
    Storage::disk($disk)->delete($path);
});

it('returns 404 when file does not exist', function () {
    // Authenticate a user
    $user = User::factory()->create();
    Auth::login($user);

    // Create import record with non-existent file
    $import = Import::create([
        'uuid' => (string) Str::uuid(),
        'user_id' => $user->id,
        'import_template_id' => null,
        'client_id' => null,
        'source_type' => 'csv',
        'file_name' => 'missing.csv',
        'original_name' => 'missing.csv',
        'disk' => 'local',
        'path' => 'imports/nonexistent.csv',
        'size' => 0,
        'status' => 'uploaded',
        'meta' => ['has_header' => true],
    ]);

    // Test download endpoint
    $response = test()->get(route('imports.download', ['import' => $import->id]));

    $response->assertNotFound();
});
