Skip to main content
Crie um cliente centralizado para não repetir headers e tratamento de erros em cada chamada.
// cordialy.ts
export class CordialyClient {
  private baseUrl = 'https://api.cordialy.ai/integrations/v1';

  constructor(private apiKey: string) {}

  private async request<T>(
    method: string,
    path: string,
    body?: unknown
  ): Promise<T> {
    const res = await fetch(`${this.baseUrl}${path}`, {
      method,
      headers: {
        'X-API-Key': this.apiKey,
        'Content-Type': 'application/json',
      },
      body: body ? JSON.stringify(body) : undefined,
    });

    if (!res.ok) {
      const err = await res.json().catch(() => ({}));
      throw new Error(`[${res.status}] ${err.message || 'Erro desconhecido'}`);
    }

    return res.json();
  }

  // Leads
  leads = {
    list: (params?: Record<string, string>) => {
      const qs = params ? '?' + new URLSearchParams(params) : '';
      return this.request('GET', `/leads${qs}`);
    },
    create: (data: { customer_phone: string; name?: string; status?: string }) =>
      this.request('POST', '/leads', data),
    get: (id: string) => this.request('GET', `/leads/${id}`),
    update: (id: string, data: object) => this.request('PATCH', `/leads/${id}`, data),
    sendMessage: (id: string, message: string) =>
      this.request('POST', `/leads/${id}/messages`, { message }),
    messages: (id: string) => this.request('GET', `/leads/${id}/messages`),
  };

  // Sellers
  sellers = {
    list: () => this.request('GET', '/sellers'),
    create: (data: { name: string; whatsapp_id: string }) =>
      this.request('POST', '/sellers', data),
    update: (id: string, data: object) => this.request('PATCH', `/sellers/${id}`, data),
    delete: (id: string) => this.request('DELETE', `/sellers/${id}`),
  };

  // Follow-ups
  followups = {
    configs: () => this.request('GET', '/followups/configs'),
    schedule: (data: { lead_id: string; config_id: string; scheduled_at?: string }) =>
      this.request('POST', '/followups/scheduled', data),
    cancel: (id: string) => this.request('DELETE', `/followups/scheduled/${id}`),
  };
}

// Uso:
const cordialy = new CordialyClient(process.env.CORDIALY_API_KEY!);

const lead = await cordialy.leads.create({ customer_phone: '5511999998888', name: 'João' });
await cordialy.leads.sendMessage(lead.id, 'Olá João!');