import { NextResponse } from "next/server";
import { z } from "zod";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getAuditRecommendations } from "@/lib/services/audit-recommendations";
import { validateQuery } from "@/lib/validation/request";
import { BrandIdSchema } from "@/lib/validation/common-schemas";
import { withErrorHandler } from "@/lib/api/with-error-handler";

const QuerySchema = z.object({
  brandId: BrandIdSchema,
  source: z.string().optional(),
  severity: z.string().optional(),
});

/**
 * GET /api/audit-recommendations?brandId=xxx
 * GET /api/audit-recommendations?brandId=xxx&source=technical_audit
 * GET /api/audit-recommendations?brandId=xxx&severity=critical
 *
 * Returns a unified list of recommendations from all audit sources,
 * sorted by severity (critical first).
 */
export const dynamic = "force-dynamic";

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

  const { brandId, source, severity } = validateQuery(req, QuerySchema);

  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand || !brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  let recs = await getAuditRecommendations(brandId);

  // Optional filters
  if (source) recs = recs.filter((r) => r.source === source);
  if (severity) recs = recs.filter((r) => r.severity === severity);

  return NextResponse.json({
    total: recs.length,
    bySeverity: {
      critical: recs.filter((r) => r.severity === "critical").length,
      high: recs.filter((r) => r.severity === "high").length,
      medium: recs.filter((r) => r.severity === "medium").length,
      low: recs.filter((r) => r.severity === "low").length,
    },
    bySource: {
      technical_audit: recs.filter((r) => r.source === "technical_audit").length,
      dead_pages: recs.filter((r) => r.source === "dead_pages").length,
      performance_audit: recs.filter((r) => r.source === "performance_audit").length,
      ai_visibility: recs.filter((r) => r.source === "ai_visibility").length,
      competitors: recs.filter((r) => r.source === "competitors").length,
    },
    recommendations: recs,
  });
});
