<?php

declare(strict_types=1);

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

uses(DatabaseTransactions::class, SharesSupplierPdo::class);

beforeEach(function () {
    $this->tenant = Tenant::factory()->create(['contact_email' => 'tenant-admin@example.ru']);
    // verify() делает session-takeover активного юзера тенанта (G7-B) → без него 422.
    User::factory()->create(['tenant_id' => $this->tenant->id, 'is_active' => true]);
    $this->adminId = DB::table('saas_admin_users')->insertGetId([
        'email' => 'admin-saas-'.uniqid().'@liderra.ru',
        'full_name' => 'SaaS Admin',
        'password_hash' => '$2y$04$dummy-hash-for-test',
        'role' => 'support',
        'is_active' => true,
        'sso_provider' => 'local',
        'is_break_glass' => false,
    ]);
});

it('init writes saas_admin_audit_log impersonation.init', function () {
    $reason = 'support investigation '.str_repeat('x', 30);
    $r = $this->postJson('/api/admin/impersonation/init', [
        'tenant_id' => $this->tenant->id,
        'requested_by' => $this->adminId,
        'reason' => $reason,
    ])->assertOk();

    $row = DB::table('saas_admin_audit_log')->where('action', 'impersonation.init')->latest('id')->first();
    expect($row)->not->toBeNull()
        ->and((int) $row->admin_user_id)->toBe($this->adminId)
        ->and((int) $row->target_id)->toBe($this->tenant->id)
        ->and($row->reason)->toBe($reason);
});

it('verify writes saas_audit impersonation.verify + pd_processing_log viewed', function () {
    $token = ImpersonationToken::create([
        'tenant_id' => $this->tenant->id, 'requested_by' => $this->adminId,
        'code_hash' => Hash::make('123456'),
        'reason' => 'verify case '.str_repeat('y', 30),
        'sent_to_email' => 'a@b.ru', 'expires_at' => now()->addMinutes(15),
    ]);

    $this->postJson('/api/admin/impersonation/verify', ['token_id' => $token->id, 'code' => '123456'])->assertOk();

    expect(DB::table('saas_admin_audit_log')->where('action', 'impersonation.verify')->count())->toBe(1)
        ->and(DB::table('pd_processing_log')
            ->where('action', 'viewed')
            ->where('purpose', 'impersonation_session_'.$token->id)
            ->where('actor_admin_user_id', $this->adminId)
            ->count())->toBe(1);
});

it('end writes saas_admin_audit_log impersonation.end', function () {
    $token = ImpersonationToken::create([
        'tenant_id' => $this->tenant->id, 'requested_by' => $this->adminId,
        'code_hash' => Hash::make('123456'),
        'reason' => 'end case '.str_repeat('z', 30),
        'sent_to_email' => 'a@b.ru', 'expires_at' => now()->addMinutes(15),
        'used_at' => now()->subMinutes(5),
    ]);

    $this->postJson('/api/admin/impersonation/end', ['token_id' => $token->id])->assertOk();

    expect(DB::table('saas_admin_audit_log')->where('action', 'impersonation.end')->count())->toBe(1);
});
