/**
 * POST /api/analysis/share  { analysisJobId }
 * Enables sharing and returns the share token/URL.
 *
 * DELETE /api/analysis/share  { analysisJobId }
 * Disables sharing for the analysis.
 *
 * GET /api/analysis/share?token=xxx
 * Returns the shared analysis (no auth required — token is the access key).
 */

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

export const dynamic = "force-dynamic";

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

  const { analysisJobId } = 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") {
    return NextResponse.json({ error: "Only completed analyses can be shared" }, { status: 400 });
  }

  // Generate token if not already set
  const token = job.shareToken ?? randomBytes(24).toString("base64url");

  await prisma.analysisJob.update({
    where: { id: analysisJobId },
    data: { shareToken: token, shareEnabled: true },
  });

  const baseUrl = process.env.NEXT_PUBLIC_APP_URL ?? "";
  return NextResponse.json({
    shareToken: token,
    shareUrl: `${baseUrl}/analysis/${token}`,
    shareEnabled: true,
  });
}

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

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

  await prisma.analysisJob.update({
    where: { id: analysisJobId },
    data: { shareEnabled: false },
  });

  return NextResponse.json({ shareEnabled: false });
}

// ── Fetch shared analysis (no auth — token is the key) ──
export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const token = searchParams.get("token");
  if (!token) return NextResponse.json({ error: "token required" }, { status: 400 });

  const job = await prisma.analysisJob.findFirst({
    where: { shareToken: token, shareEnabled: true, status: "completed" },
    select: { result: true, branding: true, createdAt: true, completedAt: true },
  });

  if (!job || !job.result) {
    return NextResponse.json({ error: "Analysis not found or sharing is disabled" }, { status: 404 });
  }

  return NextResponse.json({
    analysis: job.result,
    branding: job.branding,
    sharedAt: job.completedAt?.toISOString() ?? job.createdAt.toISOString(),
  });
}
