<?php
namespace EasyChat\Library\Crm;

final class Bitrix24Webhook {
    public static function normalize(string $value): string {
        $value = trim($value);
        if ($value === '' || preg_match('/[\x00-\x20\x7f\\\\]/', $value)) {
            return '';
        }
        $parts = parse_url($value);
        if (!is_array($parts)
            || strtolower((string)($parts['scheme'] ?? '')) !== 'https'
            || isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment'])
            || (isset($parts['port']) && (int)$parts['port'] !== 443)
        ) {
            return '';
        }
        $host = strtolower(trim((string)($parts['host'] ?? ''), '.'));
        $path = '/' . trim((string)($parts['path'] ?? ''), '/');
        if ($host === '' || filter_var($host, FILTER_VALIDATE_IP) !== false
            || !preg_match('#^/rest/[1-9][0-9]*/[A-Za-z0-9_-]{8,128}$#', $path)
        ) {
            return '';
        }
        return 'https://' . $host . $path;
    }

    public static function masked(string $value): string {
        $normalized = self::normalize($value);
        if ($normalized === '') return '';
        $parts = parse_url($normalized);
        $segments = explode('/', trim((string)$parts['path'], '/'));
        return 'https://' . $parts['host'] . '/rest/' . ($segments[1] ?? '…') . '/••••••••';
    }
}
