<?php
declare(strict_types=1);

namespace KbMarkdownImporter\Import;

final class ImportLogger
{
    private const OPTION = 'kb_markdown_importer_logs';
    private const LIMIT = 300;

    public static function info(string $message): void
    {
        self::log('INFO', $message);
    }

    public static function warning(string $message): void
    {
        self::log('WARNING', $message);
    }

    public static function error(string $message): void
    {
        update_option('kb_markdown_importer_last_error', self::sanitize($message), false);
        self::log('ERROR', $message);
    }

    public static function debug(string $message): void
    {
        self::log('DEBUG', $message);
    }

    public static function recent(int $limit = 50): array
    {
        $logs = array_reverse((array) get_option(self::OPTION, []));
        return array_slice($logs, 0, $limit);
    }

    private static function log(string $level, string $message): void
    {
        $logs = (array) get_option(self::OPTION, []);
        $logs[] = [
            'time' => current_time('mysql'),
            'level' => $level,
            'message' => self::sanitize($message),
        ];

        if (count($logs) > self::LIMIT) {
            $logs = array_slice($logs, -self::LIMIT);
        }

        update_option(self::OPTION, $logs, false);
    }

    private static function sanitize(string $message): string
    {
        $message = preg_replace('/([?&](?:private_)?token=)[^&\s]+/i', '$1[redacted]', $message) ?? $message;
        $message = preg_replace('/(PRIVATE-TOKEN|Authorization):\s*\S+/i', '$1: [redacted]', $message) ?? $message;

        return sanitize_text_field($message);
    }
}
