<?php

declare(strict_types=1);

namespace App\Http\Controllers\Concerns;

use Illuminate\Support\Facades\DB;

/**
 * Запись в auth_log (защищён hash-chain тригером).
 * Используется в AuthController, TwoFactorController,
 * TwoFactorSetupController, PasswordResetController — единственная
 * точка записи auth-событий.
 *
 * Канонические event-strings (расширяемо):
 *   login_success, login_failed, logout, register_success,
 *   2fa_verify_success, 2fa_verify_failed, 2fa_recovery_used, 2fa_recovery_failed,
 *   2fa_setup_init, 2fa_setup_confirmed, 2fa_disabled, 2fa_recovery_regenerated,
 *   password_reset_requested, password_reset_completed, password_reset_failed
 */
trait WritesAuthLog
{
    protected function logAuthEvent(
        string $event,
        ?int $userId,
        ?int $tenantId,
        ?string $email,
        ?string $ip,
        ?string $userAgent,
        ?string $failureReason,
    ): void {
        DB::table('auth_log')->insert([
            'actor_type' => 'tenant_user',
            'tenant_id' => $tenantId,
            'user_id' => $userId,
            'email' => $email,
            'event' => $event,
            'ip_address' => $ip,
            'user_agent' => $userAgent,
            'failure_reason' => $failureReason,
            'created_at' => now(),
        ]);
    }
}
