import { Platform } from 'react-native';
import { API_URL, APP_VERSION } from 'src/constants';

export async function testConnectionSpeed({ bytes = 2_000_000, timeout = 10_000 } = {}) {
  const pingUrl = `${API_URL}/app/speed-ping`;
  const downloadUrl = `${API_URL}/app/speed-bytes`;

  const fetchWithTimeout = async (url: string, options = {}) => {
    const controller = new AbortController();
    const id = setTimeout(() => controller.abort(), timeout);
    try {
      const res = await fetch(url, {
        ...options,
        signal: controller.signal,
        headers: {
          Platform: Platform.OS,
          'App-Version': APP_VERSION
        }
      });
      clearTimeout(id);
      return res;
    } catch (e) {
      clearTimeout(id);
      throw e;
    }
  };

  try {
    const t0 = Date.now();
    await fetchWithTimeout(pingUrl, { method: 'HEAD' });
    const ping = Date.now() - t0;

    const start = Date.now();
    const form = new FormData();
    form.append('bytes', String(bytes));

    const res = await fetchWithTimeout(downloadUrl, {
      method: 'POST',
      body: form
    });

    const contentType = res.headers.get('content-type') || '';
    if (!res.ok || !/application\/octet-stream/i.test(contentType)) {
      const text = await res.text().catch(() => '');
      console.warn('Unexpected response:', res.status, contentType, text);
      throw new Error('speed-bytes did not return binary data');
    }

    const blob = await res.blob();
    const end = Date.now();

    const seconds = (end - start) / 1000;
    const sizeMB = blob.size / (1024 * 1024);
    const downloadSpeed = Number((sizeMB / seconds).toFixed(2));

    return { ping, downloadSpeed };
  } catch (error) {
    console.error('Speed test failed:', error);
    return null;
  }
}
