<?php

declare(strict_types=1);

use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Tests\Concerns\SharesSupplierPdo;

uses(DatabaseTransactions::class);
// AdminIncidentsController читает incidents_log через DB::connection('pgsql_supplier');
// под DatabaseTransactions записи дефолтного pgsql невидимы отдельному PDO supplier'а
// → notifyRkn() abort(404). Трейт шарит один PDO между коннектами (откат сохраняется).
uses(SharesSupplierPdo::class);

beforeEach(function () {
    DB::table('incidents_log')->delete();
    $this->adminId = (int) DB::table('saas_admin_users')->insertGetId([
        'email' => 'rkn-'.bin2hex(random_bytes(3)).'@test',
        'full_name' => 'RKN Admin',
        'password_hash' => bcrypt('test1234'),
        'is_active' => true,
        'role' => 'support',
        'created_at' => now(),
    ]);
});

function makeRknIncident(int $adminId, array $overrides = []): int
{
    $started = $overrides['started_at'] ?? now()->subHours(2);

    return (int) DB::table('incidents_log')->insertGetId(array_merge([
        'type' => 'data_breach',
        'severity' => 'critical',
        'started_at' => $started,
        'detected_at' => $started,
        'summary' => 'PDN leak test',
        'created_by_admin_id' => $adminId,
        'created_at' => now(),
    ], $overrides));
}

test('POST rkn-notify проставляет rkn_notified_at + audit-log', function () {
    $id = makeRknIncident($this->adminId);
    $r = $this->postJson("/api/admin/incidents/{$id}/rkn-notify");
    $r->assertOk();
    expect($r->json('incident.rkn_notified'))->toBeTrue();
    expect($r->json('incident.rkn_notified_at'))->toBeString();
    expect(DB::table('incidents_log')->where('id', $id)->value('rkn_notified_at'))->not->toBeNull();
    expect(DB::table('saas_admin_audit_log')->where('action', 'incident.rkn_notify')->where('target_id', $id)->exists())
        ->toBeTrue();
});

test('POST rkn-notify несуществующий инцидент → 404', function () {
    $this->postJson('/api/admin/incidents/99999999/rkn-notify')->assertStatus(404);
});

test('POST rkn-notify не data_breach → 422', function () {
    $id = makeRknIncident($this->adminId, ['type' => 'service_outage']);
    $this->postJson("/api/admin/incidents/{$id}/rkn-notify")->assertStatus(422);
    expect(DB::table('incidents_log')->where('id', $id)->value('rkn_notified_at'))->toBeNull();
});

test('POST rkn-notify повторно → 409', function () {
    $id = makeRknIncident($this->adminId, ['rkn_notified_at' => now()->subHour()]);
    $this->postJson("/api/admin/incidents/{$id}/rkn-notify")->assertStatus(409);
});
