import { NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';

export async function GET() {
  try {
    const supabase = await createClient();
    const { data: cats, error } = await supabase
      .from('forum_categories')
      .select('*')
      .order('display_order', { ascending: true });

    if (error) throw error;

    // Latest thread per category — joined client-side so we keep one
    // round-trip per category instead of N+1. Each cat ends up with
    // last_thread_title + last_activity_at attached.
    const catIds = (cats || []).map((c: any) => c.id);
    let lastByCat: Record<string, { title: string; at: string }> = {};
    if (catIds.length) {
      const { data: latest } = await supabase
        .from('forum_threads')
        .select('id, category_id, title, last_reply_at, created_at')
        .in('category_id', catIds)
        .order('last_reply_at', { ascending: false, nullsFirst: false })
        .limit(2000);
      for (const t of latest || []) {
        const k = t.category_id as string;
        if (!lastByCat[k]) {
          lastByCat[k] = {
            title: t.title,
            at:    t.last_reply_at || t.created_at,
          };
        }
      }
    }
    const enriched = (cats || []).map((c: any) => ({
      ...c,
      last_thread_title: lastByCat[c.id]?.title || null,
      last_activity_at:  lastByCat[c.id]?.at    || null,
    }));

    return NextResponse.json({ categories: enriched });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
