// Adapter over outgoing WhatsApp sends. Production wraps Baileys' sock.sendMessage.
// Test mode buffers messages in memory and exposes hooks for the dev UI.

let mode = 'prod';
let prodSock = null;
const outbox = [];
const inboxHandlers = new Set();
const subscribers = new Set();

export function configureProd(sock) {
  mode = 'prod';
  prodSock = sock;
}

export function configureTest() {
  mode = 'test';
  prodSock = null;
}

export function isTestMode() {
  return mode === 'test';
}

export async function sendText(jid, text, opts = {}) {
  const msg = { jid, text, at: new Date().toISOString(), ...opts };
  if (mode === 'test') {
    outbox.push(msg);
    subscribers.forEach(fn => fn({ kind: 'out', msg }));
    return msg;
  }
  return prodSock.sendMessage(jid, { text }, opts.context || undefined);
}

export function injectInbound({ jid, fromNum, text }) {
  const msg = { jid, fromNum, text, at: new Date().toISOString() };
  subscribers.forEach(fn => fn({ kind: 'in', msg }));
  for (const handler of inboxHandlers) {
    Promise.resolve(handler(msg)).catch(err => console.error('[adapter] handler error', err));
  }
  return msg;
}

export function onInbound(fn) {
  inboxHandlers.add(fn);
  return () => inboxHandlers.delete(fn);
}

export function subscribe(fn) {
  subscribers.add(fn);
  return () => subscribers.delete(fn);
}

export function readOutbox() {
  return outbox.slice();
}

export function clearOutbox() {
  outbox.length = 0;
}

// ── Group operations (used by Hotmart-triggered onboarding) ─────────────────
// In test mode we synthesize a deterministic fake group JID so tests can
// assert the resulting state without a live socket.

let _testGroupCounter = 0;

export async function createGroup(name, participantJids = []) {
  if (mode === 'test') {
    _testGroupCounter += 1;
    const fakeJid = `test-group-${_testGroupCounter}@g.us`;
    outbox.push({ kind: 'group-create', name, participantJids, jid: fakeJid, at: new Date().toISOString() });
    subscribers.forEach(fn => fn({ kind: 'group-create', msg: { jid: fakeJid, name, participantJids } }));
    return { id: fakeJid, gid: fakeJid, name };
  }
  if (!prodSock) throw new Error('whatsappAdapter not configured (prod mode, no sock)');
  return prodSock.groupCreate(name, participantJids);
}

export async function getGroupInviteLink(groupJid) {
  if (mode === 'test') {
    return `https://chat.whatsapp.com/test-invite-for-${groupJid.split('@')[0]}`;
  }
  if (!prodSock) throw new Error('whatsappAdapter not configured (prod mode, no sock)');
  const code = await prodSock.groupInviteCode(groupJid).catch(() => null);
  return code ? `https://chat.whatsapp.com/${code}` : null;
}

export async function addToGroup(groupJid, participantJids) {
  if (mode === 'test') {
    outbox.push({ kind: 'group-add', groupJid, participantJids, at: new Date().toISOString() });
    return { added: participantJids };
  }
  if (!prodSock) throw new Error('whatsappAdapter not configured (prod mode, no sock)');
  return prodSock.groupParticipantsUpdate(groupJid, participantJids, 'add');
}

// Test-only: reset counter so deterministic group IDs in test runs.
export function _resetTestState() {
  _testGroupCounter = 0;
  outbox.length = 0;
}
