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

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

export async function sendText(payload: { number: string; text: string; mentioned?: string[] }): 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/sendText/${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 sendReaction(payload: {
  key: { remoteJid: string; id: string; fromMe: boolean; participant?: string };
  reaction: string;
}): 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/sendReaction/${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 };
  }
}
