<?php

declare(strict_types=1);

namespace App\Support\Audit;

use App\Services\Intune\SecretClassificationService;

final class AuditContextSanitizer
{
    private const REDACTED = '[REDACTED]';

    public static function sanitize(mixed $value): mixed
    {
        if (is_array($value)) {
            $sanitized = [];

            foreach ($value as $key => $item) {
                if (is_string($key) && self::classifier()->protectsField('audit', $key)) {
                    $sanitized[$key] = self::REDACTED;

                    continue;
                }

                $sanitized[$key] = self::sanitize($item);
            }

            return $sanitized;
        }

        if (is_string($value)) {
            return self::sanitizeString($value);
        }

        return $value;
    }

    private static function sanitizeString(string $value): string
    {
        $candidate = trim($value);

        if ($candidate === '') {
            return $value;
        }

        return self::classifier()->sanitizeAuditString($value);
    }

    private static function classifier(): SecretClassificationService
    {
        return app(SecretClassificationService::class);
    }
}
