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

export const runtime = 'nodejs';
export const revalidate = 300; // 5 minutes

const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const SUPABASE_ANON = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;

interface TickerItem {
  id: string;
  href: string;
  title: string;
  kind: 'thread' | 'reply';
  author_name: string | null;
  created_at: string;
}

export async function GET() {
  const sb = createClient(SUPABASE_URL, SUPABASE_ANON, {
    db: { schema: 'bb' },
    auth: { persistSession: false },
  });

  // Threads only — per editorial direction we surface unique topics, not
  // reply chatter, so the ticker shows breadth of discussion.
  const threadsRes = await sb
    .from('forum_threads')
    .select('id, title, author_name, created_at')
    .order('created_at', { ascending: false })
    .limit(40);

  if (threadsRes.error) {
    return NextResponse.json(
      { error: threadsRes.error.message, items: [] },
      { status: 500 },
    );
  }

  const items: TickerItem[] = (threadsRes.data || []).map((t: any) => ({
    id: t.id,
    href: `/forum/thread/${t.id}`,
    title: t.title,
    kind: 'thread',
    author_name: t.author_name,
    created_at: t.created_at,
  }));

  return NextResponse.json(
    { items: items.slice(0, 40) },
    {
      headers: {
        'Cache-Control': 'public, s-maxage=300, stale-while-revalidate=600',
      },
    }
  );
}
