// Persistência de leads. Estratégia dupla:
// 1. Sempre grava em arquivo JSON local (para desenvolvimento e fallback)
// 2. Se GHL_API_KEY + GHL_LOCATION_ID setados, POST no GoHighLevel
// 3. Sempre grava também na Vercel KV se disponível (produção)
//
// Renato vê leads via GET /api/leads?token=<ADMIN_TOKEN>

import fs from "node:fs/promises";
import path from "node:path";

export type Lead = {
  id: string;
  timestamp: string;
  consultor: string; // slug: renato | mary | monique | vinicius
  nome: string;
  empresa: string;
  whatsapp: string;
  email: string;
  ghl: { synced: boolean; contactId?: string; error?: string };
  ip?: string;
  userAgent?: string;
};

// Vercel serverless: só /tmp é gravável. Local/VPS: pasta "leads" no cwd.
const LEADS_FILE =
  process.env.LEADS_FILE ||
  (process.env.VERCEL ? "/tmp/leads.json" : path.join(process.cwd(), "leads", "leads.json"));

async function ensureFile() {
  const dir = path.dirname(LEADS_FILE);
  try {
    await fs.mkdir(dir, { recursive: true });
    await fs.access(LEADS_FILE);
  } catch {
    await fs.writeFile(LEADS_FILE, "[]", "utf8");
  }
}

export async function readLeads(): Promise<Lead[]> {
  await ensureFile();
  try {
    const raw = await fs.readFile(LEADS_FILE, "utf8");
    return JSON.parse(raw);
  } catch {
    return [];
  }
}

export async function appendLead(lead: Lead): Promise<void> {
  await ensureFile();
  const leads = await readLeads();
  leads.unshift(lead); // mais recente primeiro
  await fs.writeFile(LEADS_FILE, JSON.stringify(leads, null, 2), "utf8");
}

// GHL sync opcional
export async function syncToGHL(lead: Lead, ghlTag: string, eventoTag: string) {
  const apiKey = process.env.GHL_API_KEY;
  const locationId = process.env.GHL_LOCATION_ID;
  const pipelineId = process.env.GHL_PIPELINE_ID;
  const stageId = process.env.GHL_STAGE_ID;

  if (!apiKey || !locationId) {
    return { synced: false, error: "GHL env vars ausentes (rodando modo local)" };
  }

  const [firstName, ...rest] = lead.nome.trim().split(/\s+/);
  const lastName = rest.join(" ") || firstName;

  const contactPayload = {
    firstName,
    lastName,
    email: lead.email,
    phone: lead.whatsapp,
    companyName: lead.empresa,
    locationId,
    tags: [ghlTag, eventoTag],
    source: `LP CONAFOR SMART - ${lead.consultor}`,
  };

  try {
    const contactRes = await fetch("https://services.leadconnectorhq.com/contacts/", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
        Version: "2021-07-28",
      },
      body: JSON.stringify(contactPayload),
    });

    const contactText = await contactRes.text();
    let contactId: string | undefined;

    if (contactRes.ok) {
      const contactData = JSON.parse(contactText) as { contact?: { id?: string } };
      contactId = contactData.contact?.id;
    } else if (contactRes.status === 400) {
      // GHL retorna 400 com meta.contactId quando ha duplicata — reutilizar contato existente
      try {
        const errData = JSON.parse(contactText) as { meta?: { contactId?: string } };
        contactId = errData.meta?.contactId;
      } catch {}
      if (!contactId) {
        return { synced: false, error: `GHL contact ${contactRes.status}: ${contactText.slice(0, 200)}` };
      }
      // adiciona tags no contato existente pra rastrear a origem
      await fetch(`https://services.leadconnectorhq.com/contacts/${contactId}/tags`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${apiKey}`,
          "Content-Type": "application/json",
          Version: "2021-07-28",
        },
        body: JSON.stringify({ tags: [ghlTag, eventoTag] }),
      }).then(r => r.text());
    } else {
      return { synced: false, error: `GHL contact ${contactRes.status}: ${contactText.slice(0, 200)}` };
    }

    // Criar oportunidade se pipeline configurado
    if (contactId && pipelineId && stageId) {
      const oppRes = await fetch("https://services.leadconnectorhq.com/opportunities/", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${apiKey}`,
          "Content-Type": "application/json",
          Version: "2021-07-28",
        },
        body: JSON.stringify({
          pipelineId,
          pipelineStageId: stageId,
          contactId,
          name: `${lead.nome} - CONAFOR (${lead.consultor})`,
          locationId,
          status: "open",
        }),
      });
      // Sempre consumir o body pra garantir que a serverless function nao encerra
      // antes do GHL confirmar a escrita (Vercel fecha o event loop rapido).
      const oppText = await oppRes.text();
      if (!oppRes.ok) {
        return { synced: true, contactId, error: `opp ${oppRes.status}: ${oppText.slice(0, 200)}` };
      }
    }

    return { synced: true, contactId };
  } catch (e) {
    return { synced: false, error: e instanceof Error ? e.message : String(e) };
  }
}
