import { getApiBaseUrl } from './apiConfig';

function apiBase(): string {
  return getApiBaseUrl().replace(/\/+$/, '');
}

/** 차트 timeframe(1m, 1h, 4h, 1d, 1M 등)을 DB interval_code로 정규화 (월봉만 대문자 M 유지) */
export function intervalCodeForWsSubscription(timeframe: string): string {
  const t = (timeframe || '1m').trim();
  if (t === '1M' || t === 'M') return '1M';
  return t.toLowerCase();
}

export async function acquireWsCandleSubscription(market: string, intervalCode: string): Promise<void> {
  try {
    const res = await fetch(`${apiBase()}/upbit/ws-subscriptions/acquire`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        market: market.trim(),
        intervalCode: intervalCodeForWsSubscription(intervalCode),
      }),
    });
    if (!res.ok) {
      console.warn('[upbitWsSubscription] acquire HTTP', res.status);
    }
  } catch (e) {
    console.warn('[upbitWsSubscription] acquire', e);
  }
}

export async function releaseWsCandleSubscription(market: string, intervalCode: string): Promise<void> {
  try {
    const res = await fetch(`${apiBase()}/upbit/ws-subscriptions/release`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        market: market.trim(),
        intervalCode: intervalCodeForWsSubscription(intervalCode),
      }),
    });
    if (!res.ok) {
      console.warn('[upbitWsSubscription] release HTTP', res.status);
    }
  } catch (e) {
    console.warn('[upbitWsSubscription] release', e);
  }
}
