<?php

namespace CaptureRelay;

final class Log
{
    public static function write(string $event, string $message, array $context = [], string $severity = 'info'): void
    {
        global $wpdb;
        $wpdb->insert(Config::table('activity'), [
            'event_type' => sanitize_key($event),
            'severity' => sanitize_key($severity),
            'request_id' => isset($context['request_id']) ? sanitize_text_field($context['request_id']) : null,
            'device_id' => isset($context['device_id']) ? sanitize_text_field($context['device_id']) : null,
            'attachment_id' => isset($context['attachment_id']) ? absint($context['attachment_id']) : null,
            'message' => sanitize_text_field($message),
            'context' => wp_json_encode(self::redact($context)),
            'created_at' => current_time('mysql', true),
        ], ['%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s']);
    }

    private static function redact(array $context): array
    {
        $sensitive = [
            'authorization',
            'credential',
            'credential_cipher',
            'credential_envelope',
            'request_secret',
            'signature',
            'x_capturerelay_app_proof',
        ];
        foreach ($context as $key => $value) {
            $normalizedKey = strtolower(str_replace('-', '_', (string) $key));
            if (in_array($normalizedKey, $sensitive, true)) {
                unset($context[$key]);
                continue;
            }
            if (is_array($value)) {
                $context[$key] = self::redact($value);
            }
        }
        return $context;
    }
}
