<?php
namespace EasyChat\Library\Crm;

final class RetailCrmDomain {
    public static function normalize(string $value): string {
        $value = strtolower(trim($value));
        if ($value === '') return '';
        if (strpos($value, '://') === false) $value = 'https://' . $value;
        $parts = parse_url($value);
        if (!is_array($parts) || ($parts['scheme'] ?? '') !== 'https' || !empty($parts['user']) || !empty($parts['pass'])) return '';
        if (!empty($parts['port']) || !empty($parts['query']) || !empty($parts['fragment'])) return '';
        if (($parts['path'] ?? '') !== '' && ($parts['path'] ?? '') !== '/') return '';
        $host = strtolower(rtrim((string)($parts['host'] ?? ''), '.'));
        if (!preg_match('/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.retailcrm\.ru$/', $host)) return '';
        return $host;
    }
}
