<?php

use App\Models\ExportJob;
use App\Models\ImportJob;
use Illuminate\Support\Facades\Storage;

beforeEach(function () {
    Storage::fake('local');
});

test('it deletes export files past their expiry and clears file_path', function () {
    Storage::disk('local')->put('exports/old.csv', 'member_number');
    Storage::disk('local')->put('exports/fresh.csv', 'member_number');

    $expired = ExportJob::factory()->create(['file_path' => 'exports/old.csv', 'expires_at' => now()->subDay()]);
    $fresh = ExportJob::factory()->create(['file_path' => 'exports/fresh.csv', 'expires_at' => now()->addDay()]);

    $this->artisan('files:prune-expired')->assertExitCode(0);

    Storage::disk('local')->assertMissing('exports/old.csv');
    Storage::disk('local')->assertExists('exports/fresh.csv');
    expect($expired->fresh()->file_path)->toBeNull();
    expect($fresh->fresh()->file_path)->toBe('exports/fresh.csv');
});

test('it deletes import files older than 14 days and clears the path columns', function () {
    Storage::disk('local')->put('imports/old/source.csv', 'first_name,last_name');
    Storage::disk('local')->put('imports/recent/source.csv', 'first_name,last_name');

    $expired = ImportJob::factory()->create(['source_path' => 'imports/old/source.csv']);
    $expired->forceFill(['created_at' => now()->subDays(20)])->saveQuietly();

    $recent = ImportJob::factory()->create(['source_path' => 'imports/recent/source.csv']);

    $this->artisan('files:prune-expired')->assertExitCode(0);

    Storage::disk('local')->assertMissing('imports/old/source.csv');
    Storage::disk('local')->assertExists('imports/recent/source.csv');
    expect($expired->fresh()->source_path)->toBe('');
    expect($recent->fresh()->source_path)->toBe('imports/recent/source.csv');
});
