const DEFAULT_BASE = process.env.WHATSAPP_BRIDGE_URL || 'http://127.0.0.1:3210';

function baseUrl() {
  return (process.env.WHATSAPP_BRIDGE_URL || DEFAULT_BASE).replace(/\/$/, '');
}

async function request(method, route, body, { timeoutMs = 10000 } = {}) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);
  try {
    const res = await fetch(`${baseUrl()}${route}`, {
      method,
      headers: body ? { 'Content-Type': 'application/json' } : undefined,
      body: body ? JSON.stringify(body) : undefined,
      signal: controller.signal,
    });
    const text = await res.text();
    let json = null;
    try { json = text ? JSON.parse(text) : null; } catch { /* not JSON */ }
    if (!res.ok) {
      const err = new Error(json?.error || `whatsapp-bridge ${res.status}`);
      err.status = res.status;
      err.body = json || text;
      throw err;
    }
    return json;
  } finally {
    clearTimeout(timer);
  }
}

export async function getBridgeHealth() {
  try {
    return await request('GET', '/health', null, { timeoutMs: 3000 });
  } catch (err) {
    return { ok: false, error: err.message, status: err.status || null };
  }
}

export async function getPairingQr() {
  try {
    return await request('GET', '/qr', null, { timeoutMs: 3000 });
  } catch (err) {
    return { ok: false, error: err.message, status: err.status || null };
  }
}

export async function pollIncomingMessages() {
  const result = await request('GET', '/messages', null, { timeoutMs: 5000 });
  return Array.isArray(result?.messages) ? result.messages : [];
}

export async function sendWhatsAppMessage(chatId, text) {
  if (!chatId) throw new Error('chat_id is required');
  if (!text || !String(text).trim()) throw new Error('text is required');
  return request('POST', '/send', { chat_id: chatId, text: String(text) });
}

export async function sendWhatsAppDocument({ chat_id, content, filename, mimetype, caption }) {
  if (!chat_id) throw new Error('chat_id is required');
  if (!filename) throw new Error('filename is required');
  if (content == null) throw new Error('content is required');
  const buf = Buffer.isBuffer(content) ? content : Buffer.from(String(content), 'utf8');
  if (!buf.length) throw new Error('content is empty');
  return request('POST', '/send-document', {
    chat_id,
    content_base64: buf.toString('base64'),
    filename,
    mimetype: mimetype || 'application/octet-stream',
    caption: caption || undefined,
  }, { timeoutMs: 30000 });
}

export async function logoutWhatsApp() {
  // Unlinks the paired device and wipes the bridge session, then re-offers a QR.
  return request('POST', '/logout', {}, { timeoutMs: 15000 });
}

export async function setTyping(chatId, state = 'composing') {
  if (!chatId) throw new Error('chat_id is required');
  return request('POST', '/typing', { chat_id: chatId, state });
}
