<?php

declare(strict_types=1);

use App\Models\AuditLog;
use App\Models\Tenant;
use App\Models\User;
use App\Services\Compliance\AuditLogger;

it('records audit rows on model create/update/delete', function () {
    $tenant = Tenant::factory()->create();
    app()->instance('currentTenant', $tenant);

    $user = User::create([
        'tenant_id' => $tenant->id,
        'email' => 'audit@a.test',
        'password' => bcrypt('secret123'),
        'name' => 'Audit',
    ]);

    $user->update(['name' => 'Audit v2']);
    $user->delete();

    $rows = AuditLog::withoutGlobalScopes()
        ->where('model_type', User::class)
        ->where('model_id', $user->id)
        ->pluck('action')
        ->all();

    expect($rows)->toContain('created', 'updated', 'deleted');
});

it('captures auth events explicitly', function () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create(['tenant_id' => $tenant->id]);
    app()->instance('currentTenant', $tenant);

    app(AuditLogger::class)->log('auth.login_success', $user);

    expect(
        AuditLog::withoutGlobalScopes()
            ->where('action', 'auth.login_success')
            ->where('user_id', $user->id)
            ->exists()
    )->toBeTrue();
});

it('runs ISMS-P controls and persists pia report', function () {
    $exit = \Illuminate\Support\Facades\Artisan::call('compliance:pia-report', ['--format' => 'json']);
    expect($exit)->toBeIn([0, 1]); // pass or partial fail in dev — but command must complete

    $runs = \Illuminate\Support\Facades\DB::table('isms_check_runs')->count();
    expect($runs)->toBeGreaterThan(0);
});
