import { NextRequest, NextResponse } from "next/server";
import { logger } from "@/lib/logger";
import { createClient, getSupabaseAdmin } from "@/lib/supabase/server";
import { HTTP_STATUS_INTERNAL_SERVER_ERROR } from "@/lib/constants";

/**
 * GET /api/admin/leads
 * List leads with optional status filter. Returns CSV if ?format=csv.
 */
export async function GET(request: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const admin = getSupabaseAdmin();
    const { searchParams } = new URL(request.url);
    const status = searchParams.get("status");
    const format = searchParams.get("format");

    let query = admin.from("leads").select("*").order("created_at", { ascending: false });
    if (status && status !== "all") {
      query = query.eq("status", status);
    }

    const { data: leads, error } = await query.limit(500);
    if (error) throw error;

    // CSV export
    if (format === "csv") {
      const headers = ["name", "phone", "email", "company", "source", "status", "last_contact", "notes", "created_at"];
      const csvRows = [headers.join(",")];
      for (const lead of leads || []) {
        csvRows.push(headers.map((h) => {
          const val = lead[h] ?? "";
          return `"${String(val).replace(/"/g, '""')}"`;
        }).join(","));
      }
      return new NextResponse(csvRows.join("\n"), {
        headers: {
          "Content-Type": "text/csv",
          "Content-Disposition": `attachment; filename=leads-${new Date().toISOString().slice(0, 10)}.csv`,
        },
      });
    }

    return NextResponse.json({ leads: leads || [], count: leads?.length || 0 });
  } catch (error) {
    logger.error("Leads GET error:", error);
    return NextResponse.json({ error: "Failed to fetch leads" }, { status: HTTP_STATUS_INTERNAL_SERVER_ERROR });
  }
}

/**
 * POST /api/admin/leads
 * Create a new lead or bulk import (array of leads).
 */
export async function POST(request: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const admin = getSupabaseAdmin();
    const body = await request.json();

    // Support single lead or array
    const leads = Array.isArray(body) ? body : [body];
    
    const inserts = leads.map((lead) => ({
      name: lead.name || null,
      phone: lead.phone || null,
      email: lead.email || null,
      company: lead.company || null,
      source: lead.source || "manual",
      status: lead.status || "new",
      notes: lead.notes || null,
      last_contact: lead.last_contact || null,
      created_by: user.id,
    }));

    const { data, error } = await admin.from("leads").insert(inserts).select();
    if (error) throw error;

    return NextResponse.json({ leads: data, count: data?.length || 0 }, { status: 201 });
  } catch (error) {
    logger.error("Leads POST error:", error);
    return NextResponse.json({ error: "Failed to create lead" }, { status: HTTP_STATUS_INTERNAL_SERVER_ERROR });
  }
}

/**
 * PATCH /api/admin/leads
 * Update a lead's status, notes, or last_contact.
 * Body: { id, status?, notes?, last_contact? }
 */
export async function PATCH(request: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const admin = getSupabaseAdmin();
    const { id, ...updates } = await request.json();
    if (!id) return NextResponse.json({ error: "Missing lead id" }, { status: 400 });

    // Only allow certain fields
    const allowed: Record<string, unknown> = {};
    for (const key of ["status", "notes", "last_contact", "name", "phone", "email", "company", "source"]) {
      if (updates[key] !== undefined) allowed[key] = updates[key];
    }
    allowed.updated_at = new Date().toISOString();

    const { data, error } = await admin.from("leads").update(allowed).eq("id", id).select().single();
    if (error) throw error;

    return NextResponse.json({ lead: data });
  } catch (error) {
    logger.error("Leads PATCH error:", error);
    return NextResponse.json({ error: "Failed to update lead" }, { status: HTTP_STATUS_INTERNAL_SERVER_ERROR });
  }
}
