/**
 * GET  /api/brands/[brandId]/conversion-config
 * POST /api/brands/[brandId]/conversion-config
 *
 * GET:  Returns effective conversion config for every type the brand
 *       has ever captured, merged with platform defaults.
 *
 * POST: Upserts per-type overrides. Accepts:
 *   { updates: [{ conversionType, isCounted, tierOverride, displayLabel }] }
 *   Pass { reset: true } to delete all overrides and restore defaults.
 */

import { NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/prisma";
import { validateBody } from "@/lib/validation/request";
import { withErrorHandler } from "@/lib/api/with-error-handler";
import { requireUserAndBrand } from "@/lib/auth/require";
import {
  getAllEffectiveConfigs,
  getConfigForType,
  invalidateConfigCache,
} from "@/lib/conversions/brand-config";
import { getDefaultTier, humanizeType } from "@/lib/conversions/tiers";

export const dynamic = "force-dynamic";

export const GET = withErrorHandler(async (req: Request, ...args: unknown[]) => {
  const { brandId } = (args[0] as { params: { brandId: string } }).params;
  await requireUserAndBrand(brandId);

  // Enumerate all distinct conversionTypes this brand has captured
  type TypeRow = { conversionType: string };
  const typeRows = await prisma.$queryRaw<TypeRow[]>`
    SELECT DISTINCT "conversionType"
    FROM "SiteConversion"
    WHERE "brandId" = ${brandId}
    ORDER BY "conversionType"
  `.catch(() => [] as TypeRow[]);

  const brandConfigs = await getAllEffectiveConfigs(brandId);

  const items = typeRows.map((r) => {
    const cfg = getConfigForType(brandConfigs, r.conversionType);
    return {
      conversionType: r.conversionType,
      tier: cfg.tier,
      isCounted: cfg.isCounted,
      displayLabel: cfg.displayLabel,
      isCustom: cfg.isCustom,
      defaultTier: getDefaultTier(r.conversionType),
      defaultLabel: humanizeType(r.conversionType),
    };
  });

  return NextResponse.json({ items });
});

const UpdateSchema = z.object({
  updates: z.array(z.object({
    conversionType: z.string().min(1),
    isCounted: z.boolean(),
    tierOverride: z.string().nullable().optional(),
    displayLabel: z.string().nullable().optional(),
  })).optional(),
  reset: z.boolean().optional(),
});

export const POST = withErrorHandler(async (req: Request, ...args: unknown[]) => {
  const { brandId } = (args[0] as { params: { brandId: string } }).params;
  await requireUserAndBrand(brandId);

  const body = await validateBody(req, UpdateSchema);

  if (body.reset) {
    await (prisma as any).brandConversionConfig.deleteMany({ where: { brandId } });
    invalidateConfigCache(brandId);
    return NextResponse.json({ ok: true, reset: true });
  }

  const updates = body.updates ?? [];
  for (const u of updates) {
    await (prisma as any).brandConversionConfig.upsert({
      where: { brandId_conversionType: { brandId, conversionType: u.conversionType } },
      create: {
        brandId,
        conversionType: u.conversionType,
        isCounted: u.isCounted,
        tierOverride: u.tierOverride ?? null,
        displayLabel: u.displayLabel ?? null,
      },
      update: {
        isCounted: u.isCounted,
        tierOverride: u.tierOverride ?? null,
        displayLabel: u.displayLabel ?? null,
      },
    });
  }

  invalidateConfigCache(brandId);
  return NextResponse.json({ ok: true, updated: updates.length });
});
