/**
 * GET /api/technical-audit/issue?id=xxx
 * Returns a single TechnicalIssue with its parent audit metadata.
 */

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

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

  const issue = await prisma.technicalIssue.findUnique({
    where: { id },
    include: {
      audit: {
        select: {
          id: true,
          status: true,
          crawlHealth: true,
          pagesScanned: true,
          createdAt: true,
          completedAt: true,
          duration: true,
          brand: {
            select: {
              id: true,
              domain: true,
              organization: { select: { memberships: { select: { userId: true } } } },
            },
          },
        },
      },
    },
  });

  if (!issue) return NextResponse.json({ error: "Issue not found" }, { status: 404 });

  // Authorization: user must belong to the brand's org
  const members = issue.audit.brand.organization.memberships;
  if (!members.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  // Only return evidence from completed audits
  if (issue.audit.status !== "completed") {
    return NextResponse.json({ error: "Audit not completed" }, { status: 404 });
  }

  return NextResponse.json({
    id: issue.id,
    title: issue.title,
    detail: issue.detail,
    category: issue.category,
    severity: issue.severity,
    status: issue.status,
    pageUrl: issue.pageUrl,
    affectedUrls: issue.affectedUrls,
    evidence: issue.evidence,
    affected: issue.affected,
    audit: {
      id: issue.audit.id,
      crawlHealth: issue.audit.crawlHealth,
      pagesScanned: issue.audit.pagesScanned,
      completedAt: issue.audit.completedAt,
      duration: issue.audit.duration,
    },
    brandId: issue.audit.brand.id,
    domain: issue.audit.brand.domain,
  });
}
