/**
 * POST /api/analysis/client-version
 * Save a client-ready version of the analysis.
 * Body: { analysisJobId, hiddenSections?: string[] }
 *
 * GET /api/analysis/client-version?analysisJobId=xxx
 * Returns the saved client version.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import type { Analysis } from "@/lib/services/analysis-schema";

export const dynamic = "force-dynamic";

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

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

  const job = await prisma.analysisJob.findUnique({
    where: { id: analysisJobId },
    include: { brand: { include: { organization: { include: { memberships: true } } } } },
  });

  if (!job) return NextResponse.json({ error: "Analysis not found" }, { status: 404 });
  if (!job.brand.organization.memberships.some(m => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }
  if (job.status !== "completed" || !job.result) {
    return NextResponse.json({ error: "Only completed analyses can be saved as client versions" }, { status: 400 });
  }

  // Build client version: full analysis minus hidden sections
  const analysis = job.result as unknown as Analysis;
  const hidden = new Set(hiddenSections ?? []);

  const clientAnalysis: Record<string, unknown> = { ...analysis };

  // Remove hidden sections
  if (hidden.has("caveats")) clientAnalysis.caveats = [];
  if (hidden.has("methodology") && analysis.narrative) {
    clientAnalysis.narrative = { ...analysis.narrative, methodology: "" };
  }
  if (hidden.has("predictions")) clientAnalysis.predictions = [];
  if (hidden.has("timeline")) clientAnalysis.timeline = [];

  // Filter out internal-only findings (if any are marked as such in the future)
  // For now, keep all approved findings

  await prisma.analysisJob.update({
    where: { id: analysisJobId },
    data: {
      clientVersion: JSON.parse(JSON.stringify(clientAnalysis)),
      clientVersionAt: new Date(),
      hiddenSections: hiddenSections ?? [],
    },
  });

  return NextResponse.json({
    saved: true,
    hiddenSections: hiddenSections ?? [],
    savedAt: new Date().toISOString(),
  });
}

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const analysisJobId = searchParams.get("analysisJobId");
  const token = searchParams.get("token");

  let job;
  if (token) {
    // Shared access via token
    job = await prisma.analysisJob.findFirst({
      where: { shareToken: token, shareEnabled: true },
      select: { clientVersion: true, clientVersionAt: true, hiddenSections: true, result: true },
    });
  } else if (analysisJobId) {
    const user = await getCurrentUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    job = await prisma.analysisJob.findUnique({
      where: { id: analysisJobId },
      select: { clientVersion: true, clientVersionAt: true, hiddenSections: true, result: true },
    });
  }

  if (!job) return NextResponse.json({ error: "Not found" }, { status: 404 });

  // Return client version if saved, otherwise return the full analysis
  return NextResponse.json({
    analysis: job.clientVersion ?? job.result,
    isClientVersion: !!job.clientVersion,
    savedAt: job.clientVersionAt?.toISOString() ?? null,
    hiddenSections: job.hiddenSections ?? [],
  });
}
