<?php
namespace EasyChat\Library\Messenger;

use EasyChat\Library\Logger;
use EasyChat\Model\Setting;

class MessengerLogger {

    private $enabled;
    private $provider_code;

    public function __construct($registry, string $provider_code = 'max-bot') {
        $this->provider_code = strtolower($provider_code);
        $model_setting = new Setting($registry);
        $setting_key = 'chat_' . str_replace('-', '_', $this->provider_code) . '_logging';
        $this->enabled = $model_setting->get($setting_key, '0') === '1';
    }

    public function info(string $message, array $context = []): void {
        $this->write('INFO', $message, $context);
    }

    public function warning(string $message, array $context = []): void {
        $this->write('WARNING', $message, $context);
    }

    public function error(string $message, array $context = []): void {
        $this->write('ERROR', $message, $context);
    }

    private function write(string $level, string $message, array $context): void {
        if (!$this->enabled) {
            return;
        }
        $safe_context = [];
        foreach ($context as $key => $value) {
            $normalized_key = strtolower(trim((string)$key));
            if (preg_match('/token|secret|payload|text|url|phone|telephone|recipient|sender|address|body|content|preview/i', $normalized_key)
                || in_array($normalized_key, ['from', 'to', 'message', 'external_id', 'external_user_id'], true)) {
                continue;
            }
            if (is_scalar($value) || $value === null) {
                $safe_context[$key] = $value;
            }
        }
        $line = $message;
        if ($safe_context) {
            $line .= ' ' . json_encode($safe_context, JSON_UNESCAPED_UNICODE);
        }
        Logger::write('[' . $level . '] ' . $line, $this->provider_code . '.log');
    }

    public static function hashExternalId(string $id): string {
        return substr(hash('sha256', $id), 0, 16);
    }
}
