<?php

declare(strict_types=1);

namespace App\Services\Pd;

use App\Models\ImpersonationToken;
use App\Models\SaasAdminAuditLog;

/**
 * Оркестратор аудита impersonation: пишет защищённый saas_admin_audit_log
 * на init/verify/end и ПДн-след (pd_processing_log) на verify — вход админа
 * в кабинет тенанта = массовый доступ к ПДн (152-ФЗ).
 */
final class ImpersonationAuditService
{
    public function __construct(private readonly PdAuditLogger $pd) {}

    public function recordInit(ImpersonationToken $t, int $adminId, ?string $ip): void
    {
        SaasAdminAuditLog::create([
            'admin_user_id' => $adminId,
            'action' => 'impersonation.init',
            'target_type' => 'tenant',
            'target_id' => $t->tenant_id,
            'target_tenant_id' => $t->tenant_id,
            'payload_before' => null,
            'payload_after' => ['token_id' => $t->id, 'expires_at' => $t->expires_at->toIso8601String()],
            'reason' => $t->reason,
            'ip_address' => $ip ?? '127.0.0.1',
            'user_agent' => null,
        ]);
    }

    public function recordVerify(ImpersonationToken $t, int $adminId, ?string $ip): void
    {
        SaasAdminAuditLog::create([
            'admin_user_id' => $adminId,
            'action' => 'impersonation.verify',
            'target_type' => 'tenant',
            'target_id' => $t->tenant_id,
            'target_tenant_id' => $t->tenant_id,
            'payload_before' => ['used_at' => null],
            'payload_after' => ['used_at' => now()->toIso8601String()],
            'reason' => $t->reason,
            'ip_address' => $ip ?? '127.0.0.1',
            'user_agent' => null,
        ]);
        // ПДн-след: вход админа в кабинет = массовый доступ к ПДн тенанта.
        $this->pd->record(
            action: 'viewed', subjectType: 'tenant', subjectId: $t->tenant_id,
            purpose: 'impersonation_session_'.$t->id,
            tenantId: $t->tenant_id,
            actorTenantUserId: null, actorAdminUserId: $adminId, ip: $ip,
        );
    }

    public function recordEnd(ImpersonationToken $t, int $adminId, ?string $ip): void
    {
        SaasAdminAuditLog::create([
            'admin_user_id' => $adminId,
            'action' => 'impersonation.end',
            'target_type' => 'tenant',
            'target_id' => $t->tenant_id,
            'target_tenant_id' => $t->tenant_id,
            'payload_before' => ['session_ended_at' => null],
            'payload_after' => ['session_ended_at' => now()->toIso8601String()],
            'reason' => $t->reason,
            'ip_address' => $ip ?? '127.0.0.1',
            'user_agent' => null,
        ]);
    }
}
