// src/utils/platform.ts
const SUPPORTED_PLATFORMS = ['main', 'oms', 'crm', 'pms', 'yuncai'] as const;
type PlatformCode = (typeof SUPPORTED_PLATFORMS)[number];

/**
 * 从当前域名自动解析 platform_code
 * 支持：
 *   - oms.yoe365.com       → oms
 *   - crm.yoe365.com:8080  → crm
 *   - localhost            → oms (开发默认)
 *   - 127.0.0.1            → oms
 *   - yuncai.dev.local     → yuncai
 */
export function getPlatformCode(): PlatformCode {
  let host = window.location.host;

  // 移除端口（如 :8080）
  if (host.includes(':')) {
    host = host.split(':')[0];
  }

  // 开发环境特殊映射
  const devMap: Record<string, PlatformCode> = {
    'localhost': 'oms',
    '127.0.0.1': 'oms',
    'oms.dev.local': 'oms',
    'crm.dev.local': 'crm',
    'yuncai.dev.local': 'yuncai',
    'pms.dev.local': 'pms'
  };

  if (devMap[host]) {
    return devMap[host];
  }

  // 生产环境：泛解析 *.yoe365.com
  const PROD_DOMAIN_SUFFIX = '.yoe365.com';
  if (host.endsWith(PROD_DOMAIN_SUFFIX)) {
    const subdomain = host.slice(0, -PROD_DOMAIN_SUFFIX.length);
    if (SUPPORTED_PLATFORMS.includes(subdomain as PlatformCode)) {
      return subdomain as PlatformCode;
    }
  }

  // IP 地址或未知域名 → 默认 oms（开发友好）
  if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) {
    return 'oms';
  }

  // 最终 fallback
  return 'main';
}
