import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getPageLaunches, getPageLaunchDetail, createPageLaunch, addLaunchSnapshot } from "@/lib/services/page-launches";

/**
 * GET /api/page-launches?brandId=xxx
 * GET /api/page-launches?id=xxx  (single launch detail)
 */
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);

  // Single launch detail
  const launchId = searchParams.get("id");
  if (launchId) {
    const launch = await getPageLaunchDetail(launchId);
    if (!launch) return NextResponse.json({ error: "Not found" }, { status: 404 });
    return NextResponse.json(launch);
  }

  // List by brand
  const brandId = searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId is required" }, { status: 400 });

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

  const launches = await getPageLaunches(brandId);
  return NextResponse.json(launches);
}

/**
 * POST /api/page-launches
 * action: "create" | "add_snapshot"
 */
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();

    // ── CREATE ──
    if (body.action === "create") {
      const { brandId, pageUrl, pageType } = body;
      if (!brandId || !pageUrl || !pageType) {
        return NextResponse.json({ error: "brandId, pageUrl, and pageType are required" }, { status: 400 });
      }

      // Verify access
      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 launch = await createPageLaunch({
        brandId,
        pageUrl,
        pageType,
        launchDate: body.launchDate ? new Date(body.launchDate) : undefined,
        notes: body.notes,
        baselineSessions: body.baselineSessions,
        baselineClicks: body.baselineClicks,
        baselineImpressions: body.baselineImpressions,
        baselinePosition: body.baselinePosition,
        baselineConversions: body.baselineConversions,
        baselineRevenue: body.baselineRevenue,
      });

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

    // ── ADD SNAPSHOT ──
    if (body.action === "add_snapshot") {
      const { pageLaunchId } = body;
      if (!pageLaunchId) return NextResponse.json({ error: "pageLaunchId is required" }, { status: 400 });

      const snapshot = await addLaunchSnapshot(pageLaunchId, {
        sessions: body.sessions ?? 0,
        clicks: body.clicks ?? 0,
        impressions: body.impressions ?? 0,
        position: body.position ?? 0,
        conversions: body.conversions ?? 0,
        revenue: body.revenue ?? 0,
      });

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

    return NextResponse.json({ error: "action must be create or add_snapshot" }, { status: 400 });

  } catch (e) {
    console.error("Page launch error:", e);
    return NextResponse.json({ error: "Something went wrong" }, { status: 500 });
  }
}
