import { NextRequest } from "next/server";
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
import path from "path";

// TODO: Replace file-based storage with DB (chat_leads table) in Phase 3.11
const DATA_DIR = path.join(process.cwd(), "data");
const LEADS_FILE = path.join(DATA_DIR, "chat-leads.json");

export interface ChatLead {
  id: string;
  name: string;
  email: string;
  sessionId: string;
  createdAt: string;
  notes?: string;
  contacted: boolean;
}

function readLeads(): ChatLead[] {
  if (!existsSync(LEADS_FILE)) return [];
  try {
    return JSON.parse(readFileSync(LEADS_FILE, "utf-8"));
  } catch {
    return [];
  }
}

function writeLeads(leads: ChatLead[]) {
  if (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });
  writeFileSync(LEADS_FILE, JSON.stringify(leads, null, 2), "utf-8");
}

export async function POST(req: NextRequest) {
  try {
    const { name, email, sessionId } = await req.json();

    if (!email || typeof email !== "string" || !email.includes("@")) {
      return Response.json({ error: "Valid email is required." }, { status: 400 });
    }

    const leads = readLeads();

    // Prevent duplicate leads per session
    const existing = leads.find((l) => l.sessionId === sessionId);
    if (existing) {
      return Response.json({ ok: true, duplicate: true });
    }

    const newLead: ChatLead = {
      id: crypto.randomUUID(),
      name: String(name ?? "").trim() || "Unknown",
      email: String(email).trim().toLowerCase(),
      sessionId: String(sessionId ?? crypto.randomUUID()),
      createdAt: new Date().toISOString(),
      contacted: false,
    };

    leads.unshift(newLead);
    writeLeads(leads);

    return Response.json({ ok: true });
  } catch (err) {
    console.error("[chat/lead POST]", err);
    return Response.json({ error: "Failed to save lead." }, { status: 500 });
  }
}

export async function GET() {
  try {
    const leads = readLeads();
    return Response.json({ leads });
  } catch (err) {
    console.error("[chat/lead GET]", err);
    return Response.json({ error: "Failed to read leads." }, { status: 500 });
  }
}

export async function PATCH(req: NextRequest) {
  try {
    const { id, contacted } = await req.json();
    const leads = readLeads();
    const idx = leads.findIndex((l) => l.id === id);
    if (idx === -1) return Response.json({ error: "Not found." }, { status: 404 });
    leads[idx].contacted = Boolean(contacted);
    writeLeads(leads);
    return Response.json({ ok: true });
  } catch (err) {
    console.error("[chat/lead PATCH]", err);
    return Response.json({ error: "Failed to update lead." }, { status: 500 });
  }
}
