<?php

use App\Models\ArchiveRun;
use App\Models\ArchiveSetting;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

uses(RefreshDatabase::class);

it('runs an archive setting via run-now endpoint and logs audit', function () {
    $docId = null; // Define docId earlier
    $user = User::factory()->create();
    test()->actingAs($user);

    // Insert sample document older than 200 days (minimal required columns)
    $docId = DB::table('documents')->insertGetId([
        'uuid' => (string) Str::uuid(),
        'documentable_type' => 'App\\Models\\ClientCase', // generic
        'documentable_id' => 1,
        'name' => 'Old Doc',
        'file_name' => 'old.txt',
        'original_name' => 'old.txt',
        'disk' => 'public',
        'path' => 'documents/old.txt',
        'mime_type' => 'text/plain',
        'active' => 1,
        'created_at' => now()->subDays(210),
        'updated_at' => now()->subDays(210),
    ]);

    $setting = ArchiveSetting::factory()->create([
        'entities' => [[
            'table' => 'documents',
            'conditions' => ['older_than_days' => 180],
        ]],
        'enabled' => true,
        'strategy' => 'immediate',
    ]);

    test()->post(route('settings.archive.run', $setting->id))->assertRedirect();

    $setting->refresh();
    $docRow = DB::table('documents')->where('id', $docId)->first();
    expect(ArchiveRun::count())->toBe(1)
        ->and($docRow->active)->toBe(0);
});
