import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { EMAIL_RE, isValidContactStatus, isValidDealStage, isValidTags } from "@/lib/validation";

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const statusParam = searchParams.get("status") || "ACTIVE";
  const status = isValidContactStatus(statusParam) ? statusParam : "ACTIVE";
  const q = searchParams.get("q");

  const contacts = await prisma.contact.findMany({
    where: {
      status,
      ...(q
        ? {
            OR: [
              { email: { contains: q } },
              { name: { contains: q } },
              { company: { contains: q } },
            ],
          }
        : {}),
    },
    orderBy: { updatedAt: "desc" },
  });

  return NextResponse.json(contacts);
}

export async function POST(req: NextRequest) {
  const body = await req.json();
  const { name, company, email, phone, tags, dealStage, notes, source } = body;

  if (!email || typeof email !== "string" || !EMAIL_RE.test(email)) {
    return NextResponse.json({ error: "A valid email is required" }, { status: 400 });
  }
  if (dealStage !== undefined && !isValidDealStage(dealStage)) {
    return NextResponse.json({ error: "Invalid dealStage" }, { status: 400 });
  }
  if (tags !== undefined && !isValidTags(tags)) {
    return NextResponse.json({ error: "tags must be an array of short strings" }, { status: 400 });
  }

  const normalizedEmail = email.toLowerCase();
  const existing = await prisma.contact.findUnique({ where: { email: normalizedEmail } });
  if (existing) {
    return NextResponse.json(
      { error: `A contact with ${normalizedEmail} already exists`, contactId: existing.id },
      { status: 409 }
    );
  }

  const contact = await prisma.contact.create({
    data: {
      name: name || null,
      company: company || null,
      email: normalizedEmail,
      phone: phone || null,
      tags: isValidTags(tags) ? tags : undefined,
      dealStage: dealStage || "NEW",
      notes: notes || null,
      source: source || "Manual add",
      status: "ACTIVE",
    },
  });

  return NextResponse.json(contact, { status: 201 });
}
