import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { attachAuthorUsernames, buildAuthorUsernameMap } from '@/lib/forum/authorUsernames';

export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    const supabase = await createClient();

    // Fetch thread
    const { data: thread, error: threadError } = await supabase
      .from('forum_threads')
      .select('*, forum_categories(id, name, slug)')
      .eq('id', id)
      .single();

    if (threadError) throw threadError;

    // Increment view count
    await supabase
      .from('forum_threads')
      .update({ view_count: (thread.view_count || 0) + 1 })
      .eq('id', id);

    // Fetch replies
    const { data: replies, error: repliesError } = await supabase
      .from('forum_replies')
      .select('*')
      .eq('thread_id', id)
      .order('created_at', { ascending: true });

    if (repliesError) throw repliesError;

    const usernameMap = await buildAuthorUsernameMap(supabase);
    const [threadWithUsername] = attachAuthorUsernames([thread], usernameMap);

    return NextResponse.json({
      thread: threadWithUsername,
      replies: attachAuthorUsernames(replies, usernameMap),
    });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
