/**
 * GET /api/site-tag-analytics/embedded-conversions/details
 *
 * Returns paginated individual conversions for the drill-down modal.
 * Filters by provider, URL, or channel.
 *
 * Query params:
 *   brandId     (required)
 *   filterType  ('provider' | 'url' | 'channel')
 *   filterValue (value to match)
 *   days        (default 30)
 *   page        (default 0, zero-indexed)
 */

import { NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/prisma";
import { validateQuery } from "@/lib/validation/request";
import { BrandIdSchema, DaysSchema, PageSchema } from "@/lib/validation/common-schemas";
import { withErrorHandler } from "@/lib/api/with-error-handler";
import { requireUserAndBrand } from "@/lib/auth/require";
import { countedConversionWhere } from "@/lib/conversions/counted-where";

const NON_EMBEDDED_PROVIDERS = ["native", "custom", "gtag_intercept"];

export const dynamic = "force-dynamic";
const PAGE_SIZE = 50;

const QuerySchema = z.object({
  brandId: BrandIdSchema,
  filterType: z.enum(["provider", "url", "channel"]).optional(),
  filterValue: z.string().optional(),
  days: DaysSchema,
  page: PageSchema,
});

export const GET = withErrorHandler(async (req: Request) => {
  const { brandId, filterType, filterValue, days, page } = validateQuery(req, QuerySchema);
  await requireUserAndBrand(brandId);

  const from = new Date(Date.now() - days * 86_400_000);

  const filterClause: Record<string, unknown> = {};
  if (filterType === "provider" && filterValue) filterClause.formProvider = filterValue;
  if (filterType === "url" && filterValue) filterClause.pageUrl = filterValue;
  if (filterType === "channel" && filterValue) filterClause.firstTouchChannel = filterValue;

  const where = {
    ...countedConversionWhere(brandId, { since: from }),
    formProvider: { not: null as string | null, notIn: NON_EMBEDDED_PROVIDERS },
    ...filterClause,
  };

  const [conversions, total] = await Promise.all([
    prisma.siteConversion.findMany({
      where,
      orderBy: { timestamp: "desc" },
      skip: page * PAGE_SIZE,
      take: PAGE_SIZE,
      select: {
        id: true,
        conversionType: true,
        formProvider: true,
        providerCategory: true,
        pageUrl: true,
        firstTouchChannel: true,
        lastTouchChannel: true,
        sessionId: true,
        smsKeyword: true,
        smsConsentMethod: true,
        detectionMethod: true,
        timestamp: true,
      },
    }),
    prisma.siteConversion.count({ where }),
  ]);

  return NextResponse.json({
    conversions,
    pagination: {
      total,
      page,
      pageSize: PAGE_SIZE,
      totalPages: Math.ceil(total / PAGE_SIZE),
    },
  });
});
