const DEFAULT_PROD_API_ORIGIN = 'https://work.api.shumengya.top';

const stripTrailingSlashes = (value) => value.replace(/\/+$/, '');

const stripApiSuffix = (value) => value.replace(/\/api\/?$/, '');

const hasHttpProtocol = (value) => /^https?:\/\//i.test(value);

export const getApiBaseUrl = () => {
  const envUrl = process.env.REACT_APP_API_URL;
  if (envUrl) {
    const normalized = stripTrailingSlashes(envUrl);

    // 避免生产环境错误使用相对路径（例如 /api），导致请求打到前端自身域名
    if (normalized.startsWith('/')) {
      if (process.env.NODE_ENV === 'production') {
        // eslint-disable-next-line no-console
        console.warn(
          `[SproutWorkCollect] REACT_APP_API_URL=${normalized} 是相对路径，已忽略并回退到默认后端：${DEFAULT_PROD_API_ORIGIN}/api`,
        );
        return `${DEFAULT_PROD_API_ORIGIN}/api`;
      }

      return normalized.endsWith('/api') ? normalized : `${normalized}/api`;
    }

    const absolute = hasHttpProtocol(normalized) ? normalized : `https://${normalized}`;
    return absolute.endsWith('/api') ? absolute : `${absolute}/api`;
  }

  if (process.env.NODE_ENV === 'production') {
    return `${DEFAULT_PROD_API_ORIGIN}/api`;
  }

  return 'http://localhost:5000/api';
};

export const getApiOrigin = () => stripApiSuffix(getApiBaseUrl());
