/**
 * PATCH /api/site-tag/analytics/ai-attribution/outcome
 *
 * Updates Layer 6 (outcome) on an AiAttribution record.
 * Body: { attributionId, leadType, dealValue, dealStatus }
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

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

  const body = await req.json().catch(() => null);
  if (!body?.attributionId) {
    return NextResponse.json({ error: "attributionId required" }, { status: 400 });
  }

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

  const updated = await prisma.aiAttribution.update({
    where: { id: body.attributionId },
    data: {
      leadType: body.leadType ?? undefined,
      dealValue: typeof body.dealValue === "number" ? body.dealValue : undefined,
      dealStatus: body.dealStatus ?? undefined,
      outcomeUpdatedAt: new Date(),
    },
  });

  return NextResponse.json({ ok: true, attribution: updated });
}
