const GHL_API_BASE = "https://services.leadconnectorhq.com"; const GHL_API_VERSION = "2021-07-28"; export async function createGHLContact(data: { email: string; firstName?: string; lastName?: string; phone?: string; company?: string; source?: string; tags?: string[]; }) { const locationId = process.env.GHL_LOCATION_ID; const apiToken = process.env.GHL_API_TOKEN; if (!locationId || !apiToken) { console.warn("GHL credentials incomplete; skipping contact creation."); return null; } const nameParts = data.firstName || data.lastName ? { first_name: data.firstName || "", last_name: data.lastName || "", } : {}; const body: Record = { location_id: locationId, email: data.email, ...nameParts, ...(data.phone && { phone: data.phone }), ...(data.company && { company_name: data.company }), ...(data.source && { source: data.source }), ...(data.tags?.length && { tags: data.tags }), }; const res = await fetch(`${GHL_API_BASE}/contacts/`, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", Version: GHL_API_VERSION, Authorization: `Bearer ${apiToken}`, }, body: JSON.stringify(body), cache: "no-store", }); if (!res.ok) { const text = await res.text(); console.error("GHL contact creation failed:", res.status, text); return null; } return res.json(); }