<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Artisan;
use Tests\TestCase;

class DatabasePerformanceCheckTest extends TestCase
{
    use RefreshDatabase;

    public function test_database_performance_preflight_passes_with_expected_reporting_indexes(): void
    {
        $exitCode = Artisan::call('database:performance-check', ['--json' => true]);
        $report = json_decode(Artisan::output(), true, flags: JSON_THROW_ON_ERROR);

        $this->assertSame(0, $exitCode);
        $this->assertSame('healthy', $report['status']);
        $this->assertSame('pass', $report['checks']['financial_account_transactions']['status']);
        $this->assertSame('pass', $report['checks']['accounting_entries']['status']);
        $this->assertSame('pass', $report['checks']['loans']['status']);
        $this->assertSame('pass', $report['checks']['customers']['status']);
        $this->assertSame('pass', $report['checks']['management_alerts']['status']);
        $this->assertSame('pass', $report['checks']['audit_logs']['status']);
    }

    public function test_explain_mode_is_safe_on_non_mysql_test_connections(): void
    {
        $exitCode = Artisan::call('database:performance-check', [
            '--json' => true,
            '--explain' => true,
        ]);
        $report = json_decode(Artisan::output(), true, flags: JSON_THROW_ON_ERROR);

        $this->assertSame(0, $exitCode);
        $this->assertSame('healthy', $report['status']);

        if ($report['connection'] !== 'mysql') {
            $this->assertSame('skipped', $report['plans']['status']);
        }
    }

    public function test_database_performance_command_is_registered(): void
    {
        $this->assertArrayHasKey('database:performance-check', Artisan::all());
    }
}
