export type EvolutionResult = { ok: boolean; status?: number; error?: string };

function buildHeaders(): HeadersInit {
  return {
    apikey: process.env.EVOLUTION_API_KEY || '',
    'Content-Type': 'application/json'
  };
}

/** Shared helper: POST to the Evolution API endpoint, returning a standard result. */
async function evolutionPost(endpoint: string, payload: unknown): Promise<EvolutionResult> {
  const baseUrl = process.env.EVOLUTION_API_URL;
  const instance = process.env.EVOLUTION_API_INSTANCE;
  if (!baseUrl || !instance) {
    const msg = 'Missing EVOLUTION_API_URL or EVOLUTION_API_INSTANCE';
    return { ok: false, error: msg };
  }
  const url = `${baseUrl}/message/${endpoint}/${instance}`;
  try {
    const res = await fetch(url, {
      method: 'POST',
      headers: buildHeaders(),
      body: JSON.stringify(payload)
    });
    if (!res.ok) {
      const body = await res.text().catch(() => '');
      const errTxt = body?.slice(0, 200) || `HTTP ${res.status}`;
      return { ok: false, status: res.status, error: errTxt };
    }
    return { ok: true, status: res.status };
  } catch (err) {
    const errMsg = err instanceof Error ? err.message : String(err);
    return { ok: false, error: errMsg };
  }
}

export async function sendText(payload: { number: string; text: string; mentioned?: string[] }): Promise<EvolutionResult> {
  return evolutionPost('sendText', payload);
}

export async function sendReaction(payload: {
  key: { remoteJid: string; id: string; fromMe: boolean; participant?: string };
  reaction: string;
}): Promise<EvolutionResult> {
  return evolutionPost('sendReaction', payload);
}
