import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { scoreBrief } from "@/lib/services/content-scoring";

/**
 * GET /api/content-briefs/score?id=xxx
 * Returns the current scores for a brief.
 *
 * POST /api/content-briefs/score
 * Recalculates and saves scores for a brief.
 * Body: { briefId: string }
 */
export const dynamic = "force-dynamic";

async function verifyBriefAccess(briefId: string, userId: string) {
  const brief = await prisma.contentBrief.findUnique({
    where: { id: briefId },
    include: { brand: { include: { organization: { include: { memberships: true } } } } },
  });
  if (!brief) return { error: "Not found" as const, status: 404 };
  if (!brief.brand.organization.memberships.some((m) => m.userId === userId)) {
    return { error: "Access denied" as const, status: 403 };
  }
  return { brief };
}

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 briefId = searchParams.get("id");
  if (!briefId) return NextResponse.json({ error: "id is required" }, { status: 400 });

  const access = await verifyBriefAccess(briefId, user.id);
  if ("error" in access) return NextResponse.json({ error: access.error }, { status: access.status });

  return NextResponse.json({
    contentScore: access.brief.contentScore,
    subScores: access.brief.subScores,
  });
}

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

  try {
    const { briefId } = await req.json();
    if (!briefId) return NextResponse.json({ error: "briefId is required" }, { status: 400 });

    const access = await verifyBriefAccess(briefId, user.id);
    if ("error" in access) return NextResponse.json({ error: access.error }, { status: access.status });
    const brief = access.brief;

    const { contentScore, subScores } = scoreBrief({
      type: brief.type as "seo" | "llmo",
      primaryKeyword: brief.primaryKeyword,
      secondaryKeywords: brief.secondaryKeywords,
      primaryTopic: brief.primaryTopic,
      longTailKeywords: brief.longTailKeywords,
      conversationalPhrases: brief.conversationalPhrases,
      relatedQuestions: brief.relatedQuestions,
      sections: brief.sections,
      internalLinks: brief.internalLinks,
      humanizationMode: brief.humanizationMode,
    });

    const updated = await prisma.contentBrief.update({
      where: { id: briefId },
      data: {
        contentScore,
        subScores: JSON.parse(JSON.stringify(subScores)),
      },
    });

    return NextResponse.json({
      contentScore: updated.contentScore,
      subScores: updated.subScores,
    });
  } catch {
    return NextResponse.json({ error: "Something went wrong" }, { status: 500 });
  }
}
