<?php

declare(strict_types=1);

use App\Models\ReportJob;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Tests\Concerns\SharesSupplierPdo;

// Cron reports:cleanup-expired читает ReportJob и пишет pd_processing_log через
// pgsql_supplier; без SharesSupplierPdo отдельный PDO не видит незакоммиченные
// job'ы теста → 0 удалений. Трейт шарит PDO/транзакцию.
uses(DatabaseTransactions::class, SharesSupplierPdo::class);

beforeEach(function () {
    Storage::fake('local');
    $this->tenant = Tenant::factory()->create();
    $this->user = User::factory()->create(['tenant_id' => $this->tenant->id]);
    $this->actingAs($this->user);
    DB::statement('SET app.current_tenant_id = '.(int) $this->tenant->id);
});

it('writes pd deleted when a report file is destroyed', function () {
    $job = ReportJob::create([
        'tenant_id' => $this->tenant->id,
        'user_id' => $this->user->id,
        'type' => 'deals_export',
        'parameters' => ['format' => 'csv', 'date_from' => '2026-04-01', 'date_to' => '2026-04-30'],
        'status' => ReportJob::STATUS_DONE,
        'file_path' => 'reports/'.(int) $this->tenant->id.'/test.csv',
    ]);

    $this->deleteJson("/api/reports/jobs/{$job->id}")->assertOk();

    $pd = DB::table('pd_processing_log')
        ->where('action', 'deleted')
        ->orderByDesc('id')
        ->first();

    expect($pd)->not->toBeNull()
        ->and($pd->subject_type)->toBe('lead')
        ->and($pd->purpose)->toBe('report_file_'.$job->id)
        ->and((int) $pd->actor_tenant_user_id)->toBe($this->user->id)
        ->and((int) $pd->tenant_id)->toBe((int) $this->tenant->id);
});

it('writes pd deleted (system actor) when cron cleanup-expired runs', function () {
    Storage::disk('local')->put('reports/'.(int) $this->tenant->id.'/cron1.csv', 'data');
    Storage::disk('local')->put('reports/'.(int) $this->tenant->id.'/cron2.csv', 'data');

    ReportJob::create([
        'tenant_id' => $this->tenant->id,
        'user_id' => $this->user->id,
        'type' => 'deals_export',
        'parameters' => ['format' => 'csv'],
        'status' => ReportJob::STATUS_DONE,
        'file_path' => 'reports/'.(int) $this->tenant->id.'/cron1.csv',
        'expires_at' => now()->subDay(),
    ]);
    ReportJob::create([
        'tenant_id' => $this->tenant->id,
        'user_id' => $this->user->id,
        'type' => 'deals_export',
        'parameters' => ['format' => 'csv'],
        'status' => ReportJob::STATUS_DONE,
        'file_path' => 'reports/'.(int) $this->tenant->id.'/cron2.csv',
        'expires_at' => now()->subDay(),
    ]);

    $this->artisan('reports:cleanup-expired')->assertExitCode(0);

    $rows = DB::table('pd_processing_log')
        ->where('action', 'deleted')
        ->where('purpose', 'like', 'report_cleanup_expired_%')
        ->where('tenant_id', $this->tenant->id)
        ->get();

    expect($rows)->toHaveCount(2);
    foreach ($rows as $r) {
        expect($r->actor_tenant_user_id)->toBeNull()
            ->and($r->actor_admin_user_id)->toBeNull()
            ->and($r->subject_type)->toBe('lead');
    }
});
