<?php

namespace App\Services;

use App\Models\AuditLog;
use Illuminate\Support\Facades\Auth;

class AuditLogger
{
    /**
     * Log a security/audit event.
     */
    public static function log(string $eventType, string $description, ?array $oldValues = null, ?array $newValues = null, ?int $userId = null)
    {
        try {
            $userId = $userId ?? Auth::id();

            // Mask sensitive fields if present
            $oldValues = self::maskSensitiveFields($oldValues);
            $newValues = self::maskSensitiveFields($newValues);

            AuditLog::create([
                'user_id' => $userId,
                'event_type' => $eventType,
                'description' => $description,
                'old_values' => $oldValues,
                'new_values' => $newValues,
                'ip_address' => request()->ip(),
                'user_agent' => request()->userAgent(),
            ]);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Failed to write audit log: ' . $e->getMessage());
        }
    }

    /**
     * Mask sensitive fields in an array.
     */
    private static function maskSensitiveFields(?array $data): ?array
    {
        if (is_null($data)) {
            return null;
        }

        $sensitiveKeys = ['password', 'token', 'secret', 'api_key', 'store_password', 'client_secret'];

        foreach ($data as $key => $value) {
            foreach ($sensitiveKeys as $sensitiveKey) {
                if (str_contains(strtolower($key), $sensitiveKey)) {
                    $data[$key] = '********';
                    break;
                }
            }
        }

        return $data;
    }
}
