import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getCompetitors, getCompetitorTrend, upsertCompetitor, getCompetitorRecommendations, getCompetitorSummary, CompetitorType } from "@/lib/services/competitors";
import { DateRange } from "@/lib/services/date-utils";

/**
 * GET /api/competitors?brandId=xxx&range=30d
 * GET /api/competitors?brandId=xxx&summary=true
 * GET /api/competitors?brandId=xxx&recommendations=true
 * GET /api/competitors?trendId=xxx&range=90d
 */
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);

  // Trend for a single competitor
  const trendId = searchParams.get("trendId");
  if (trendId) {
    const range = (searchParams.get("range") || "90d") as DateRange;
    const trend = await getCompetitorTrend(trendId, range);
    return NextResponse.json(trend);
  }

  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 });
  }

  if (searchParams.get("summary") === "true") {
    const range = (searchParams.get("range") || "30d") as DateRange;
    const summary = await getCompetitorSummary(brandId, range);
    return NextResponse.json(summary);
  }

  if (searchParams.get("recommendations") === "true") {
    const recs = await getCompetitorRecommendations(brandId);
    return NextResponse.json(recs);
  }

  const range = (searchParams.get("range") || "30d") as DateRange;
  const data = await getCompetitors(brandId, range);
  return NextResponse.json(data);
}

/**
 * POST /api/competitors
 * action: "upsert" — add or update a competitor
 */
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();
    if (body.action === "upsert") {
      const { brandId, name, domain } = body;
      if (!brandId || !name || !domain) {
        return NextResponse.json({ error: "brandId, name, and domain required" }, { status: 400 });
      }
      const competitor = await upsertCompetitor({
        brandId,
        name,
        domain,
        type: body.type as CompetitorType,
        strongestPage: body.strongestPage,
        whyWinning: body.whyWinning,
        watchlist: body.watchlist,
      });
      return NextResponse.json(competitor, { status: 201 });
    }

    return NextResponse.json({ error: "action must be upsert" }, { status: 400 });
  } catch {
    return NextResponse.json({ error: "Something went wrong" }, { status: 500 });
  }
}
