import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getDeals, getPipelineSummary, upsertDeal, DealStage, DealStatus, CrmSource } from "@/lib/services/crm";
import { DateRange } from "@/lib/services/date-utils";

/**
 * GET /api/crm?brandId=xxx&range=30d
 * GET /api/crm?brandId=xxx&pipeline=true
 * GET /api/crm?brandId=xxx&status=won&stage=closed_won
 */
export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand || !brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const range = (searchParams.get("range") || "30d") as DateRange;

  if (searchParams.get("pipeline") === "true") {
    const summary = await getPipelineSummary(brandId, range);
    return NextResponse.json(summary);
  }

  const deals = await getDeals(brandId, range, {
    status: searchParams.get("status") as DealStatus | undefined,
    stage: searchParams.get("stage") as DealStage | undefined,
    source: searchParams.get("source") as CrmSource | undefined,
  });
  return NextResponse.json(deals);
}

/**
 * POST /api/crm — create or update a deal
 */
export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  try {
    const body = await req.json();
    const { brandId, dealName } = body;
    if (!brandId || !dealName) return NextResponse.json({ error: "brandId and dealName required" }, { status: 400 });

    const deal = await upsertDeal({
      ...body,
      closeDate: body.closeDate ? new Date(body.closeDate) : undefined,
    });
    return NextResponse.json(deal, { status: 201 });
  } catch {
    return NextResponse.json({ error: "Something went wrong" }, { status: 500 });
  }
}
