import { NextResponse } from "next/server";
import { createClient as createSupabaseClient } from "@supabase/supabase-js";
import { logApiError } from "@/lib/api/security";

// Public-safe aggregate: how many purchases each given design/template id
// has, with no user-identifying data — used for "bestseller" / social proof
// badges in the marketplace. note_design_purchases' RLS only lets a user see
// their own rows, so this needs the service role for the aggregate count.
function getSupabaseAdmin() {
  return createSupabaseClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!,
  );
}

export async function GET(req: Request) {
  try {
    const url = new URL(req.url);
    const ids = (url.searchParams.get("ids") || "")
      .split(",")
      .map((id) => id.trim())
      .filter(Boolean)
      .slice(0, 50);
    if (ids.length === 0) return NextResponse.json({ counts: {} });

    const admin = getSupabaseAdmin();
    const { data } = await admin.from("note_design_purchases").select("design_id").in("design_id", ids);

    const counts: Record<string, number> = {};
    for (const row of data || []) {
      const key = row.design_id as string;
      counts[key] = (counts[key] || 0) + 1;
    }

    return NextResponse.json({ counts });
  } catch (error) {
    logApiError("Note design popularity GET error", error);
    return NextResponse.json({ counts: {} });
  }
}
