interface WsTokenResponse {
  token: string;
  expires_in_seconds: number;
}

interface ApiSuccessResponse<T> {
  code: number;
  message: string;
  data: T;
}

export async function requestWsToken(): Promise<string> {
  const baseUrl = import.meta.env.VITE_API_BASE_URL ?? window.location.origin;
  const response = await fetch(`${baseUrl}/api/ws/token`, {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    throw new Error(`Failed to get WS token: ${response.status} ${response.statusText}`);
  }

  const json: ApiSuccessResponse<WsTokenResponse> = await response.json();

  if (json.code !== 0) {
    throw new Error(`API error: ${json.message}`);
  }

  return json.data.token;
}

export function buildWsUrlWithToken(baseUrl: string, path: string, token?: string | null): string {
  const wsBase = baseUrl.replace(/^http/, 'ws').replace(/^https/, 'wss');
  let url = `${wsBase}${path}`;

  if (token) {
    const separator = url.includes('?') ? '&' : '?';
    url = `${url}${separator}token=${token}`;
  }

  return url;
}
