// Determine API base URL based on environment
function getApiBase(): string {
  // If VITE_API_BASE is explicitly set, use it
  if ((import.meta as any).env.VITE_API_BASE) {
    const base = (import.meta as any).env.VITE_API_BASE as string;
    // If the page is HTTPS but the override is HTTP to the same host: upgrade to HTTPS port to avoid mixed content
    try {
      const isHttpsPage = typeof window !== 'undefined' && window.location.protocol === 'https:';
      const u = new URL(base, window.location.origin);
      if (isHttpsPage && u.protocol === 'http:' && u.hostname === '159.195.9.107' && (u.port === '8081' || u.port === '')) {
        return 'https://159.195.9.107:3443';
      }
    } catch {
      // ignore URL parse issues and fall through to returned base
    }
    return base;
  }
  
  // For localhost development, use the backend server
  if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
    return 'http://localhost:8081';
  }
  
  // For production/self-hosted: choose port based on protocol to avoid mixed content
  if (window.location.hostname === '159.195.9.107') {
    const isHttps = window.location.protocol === 'https:';
    return isHttps ? 'https://159.195.9.107:3443' : 'http://159.195.9.107:8081';
  }
  
  // Default fallback
  return '';
}

export const API_BASE = getApiBase();

function getJwt() {
  try {
    const stored = localStorage.getItem('spotify-user');
    if (!stored) return null;
    const parsed = JSON.parse(stored);
    return parsed?.jwt || parsed?.token || null;
  } catch {
    return null;
  }
}

export async function apiPost<T>(path: string, body?: any, token?: string): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : getJwt() ? { Authorization: `Bearer ${getJwt()}` } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(text || `Request failed: ${res.status}`);
  }
  return res.json();
}

export async function apiGet<T>(path: string, token?: string): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, {
    headers: {
      ...(token ? { Authorization: `Bearer ${token}` } : getJwt() ? { Authorization: `Bearer ${getJwt()}` } : {}),
    },
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(text || `Request failed: ${res.status}`);
  }
  return res.json();
}

export function apiEvents(path: string): EventSource {
  // For SSE, we need a plain URL; Authorization header cannot be set on EventSource.
  // We pass the JWT as a query param. Backend should accept and validate it.
  const token = getJwt();
  const url = new URL(`${API_BASE}${path}`, window.location.origin);
  if (token) url.searchParams.set('token', token);
  return new EventSource(url.toString());
}

export async function apiPostForm<T>(path: string, form: Record<string, string>, token?: string): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      ...(token ? { Authorization: `Bearer ${token}` } : getJwt() ? { Authorization: `Bearer ${getJwt()}` } : {}),
    },
    body: new URLSearchParams(form).toString(),
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(text || `Request failed: ${res.status}`);
  }
  return res.json();
}

export async function apiDelete<T>(path: string, token?: string): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, {
    method: 'DELETE',
    headers: {
      ...(token ? { Authorization: `Bearer ${token}` } : getJwt() ? { Authorization: `Bearer ${getJwt()}` } : {}),
    },
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(text || `Request failed: ${res.status}`);
  }
  return res.json();
}


