/**
 * GET /api/site-tag-analytics/integrations?brandId=xxx
 * GET /api/site-tag-analytics/integrations?brandId=xxx&category=pixel
 *
 * Returns detected integrations for a brand, sourced from DetectedIntegration.
 * Enriches each row with description from the local registry when available.
 */

import { NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/prisma";
import { validateQuery } from "@/lib/validation/request";
import { BrandIdSchema } from "@/lib/validation/common-schemas";
import { withErrorHandler } from "@/lib/api/with-error-handler";
import { lookupEnrichment } from "@/lib/site-tag/integration-signatures";
import { requireUserAndBrand } from "@/lib/auth/require";

export const dynamic = "force-dynamic";

const QuerySchema = z.object({
  brandId: BrandIdSchema,
  category: z.string().optional(),
  status: z.string().default("active"),
});

export const GET = withErrorHandler(async (req: Request) => {
  const { brandId, category, status } = validateQuery(req, QuerySchema);
  await requireUserAndBrand(brandId);

  const where = {
    brandId,
    ...(category ? { category } : {}),
    ...(status !== "all" ? { status } : {}),
  };

  // prisma.detectedIntegration is available after `prisma db push`
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const rows = await (prisma as any).detectedIntegration.findMany({
    where,
    orderBy: [{ category: "asc" }, { lastDetectedAt: "desc" }],
    select: {
      id: true,
      name: true,
      category: true,
      vendor: true,
      version: true,
      firstDetectedAt: true,
      lastDetectedAt: true,
      detectionSources: true,
      pageCount: true,
      samplePages: true,
      evidence: true,
      status: true,
      isActive: true,
    },
  }) as Array<{
    id: string;
    name: string;
    category: string;
    vendor: string | null;
    version: string | null;
    firstDetectedAt: Date;
    lastDetectedAt: Date;
    detectionSources: string[];
    pageCount: number;
    samplePages: string[];
    evidence: unknown;
    status: string;
    isActive: boolean;
  }>;

  // Merge description from registry using detectionSources[0] as plugin_key
  const integrations = rows.map((row) => {
    const pluginKey = row.detectionSources[0] ?? "";
    const enrichment = pluginKey ? lookupEnrichment(pluginKey) : null;
    return {
      ...row,
      description: enrichment?.description ?? null,
    };
  });

  const byCategory: Record<string, number> = {};
  for (const i of integrations) {
    byCategory[i.category] = (byCategory[i.category] ?? 0) + 1;
  }

  return NextResponse.json({
    integrations,
    total: integrations.length,
    byCategory,
  });
});
