/**
 * GET /api/site-tag/issue-evidence?siteId=xxx&issueId=yyy&pageUrl=zzz
 *
 * Called by the meSEO Site Tag on a customer's live page to get
 * broken link evidence for highlighting. No auth required — uses
 * siteId for verification (same as event collection).
 *
 * Returns evidence array for the given issue on the given page.
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getCorsHeaders } from "@/lib/services/page-lifecycle";

export const dynamic = "force-dynamic";

export async function OPTIONS(req: Request) {
  return new NextResponse(null, { status: 204, headers: getCorsHeaders(req) });
}

export async function GET(req: Request) {
  const cors = getCorsHeaders(req);
  const { searchParams } = new URL(req.url);
  const siteId = searchParams.get("siteId");
  const issueId = searchParams.get("issueId");
  const pageUrl = searchParams.get("pageUrl");

  if (!siteId || !issueId) {
    return NextResponse.json({ error: "siteId and issueId required" }, { status: 400, headers: cors });
  }

  // Verify the siteId exists and is active
  const site = await prisma.trackedSite.findFirst({
    where: { siteId, status: "active" },
    select: { id: true, brandId: true },
  });

  if (!site) {
    return NextResponse.json({ error: "Site not found or inactive" }, { status: 404, headers: cors });
  }

  // Fetch the issue and its evidence
  const issue = await prisma.technicalIssue.findUnique({
    where: { id: issueId },
    select: {
      id: true,
      title: true,
      category: true,
      severity: true,
      detail: true,
      pageUrl: true,
      affectedUrls: true,
      evidence: true,
      audit: {
        select: { brandId: true, id: true },
      },
    },
  });

  if (!issue || issue.audit.brandId !== site.brandId) {
    return NextResponse.json({ error: "Issue not found" }, { status: 404, headers: cors });
  }

  // Filter evidence to the requested page URL if provided
  const allEvidence = (issue.evidence as Array<Record<string, unknown>>) ?? [];
  const filtered = pageUrl
    ? allEvidence.filter(e => {
        const source = (e.sourcePageUrl as string) ?? "";
        // Match if the evidence source page matches the requested page (normalize trailing slashes)
        return source.replace(/\/$/, "") === pageUrl.replace(/\/$/, "") ||
               source.includes(pageUrl.replace(/^https?:\/\/[^/]+/, ""));
      })
    : allEvidence;

  return NextResponse.json({
    issueId: issue.id,
    title: issue.title,
    category: issue.category,
    severity: issue.severity,
    detail: issue.detail,
    evidence: filtered.length > 0 ? filtered : allEvidence,
  }, { headers: cors });
}
