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

// GET /api/forum/following-feed?limit=20&offset=0
// Returns threads from users that the current user follows
export async function GET(req: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { searchParams } = new URL(req.url);
    const limit = Math.min(parseInt(searchParams.get('limit') || '20'), 50);
    const offset = parseInt(searchParams.get('offset') || '0');

    // Get list of users the current user follows
    const { data: followingRows } = await supabase
      .from('user_follows')
      .select('following_id')
      .eq('follower_id', user.id);

    const followingIds = (followingRows || []).map((r: any) => r.following_id);

    if (followingIds.length === 0) {
      return NextResponse.json({ threads: [], total: 0, hasMore: false });
    }

    // Fetch threads from followed users
    const { data: threads, count } = await supabase
      .from('forum_threads')
      .select(
        'id, title, body, vote_score, upvotes, reply_count, view_count, created_at, author_id, forum_categories(id, name, slug), user_profiles!forum_threads_author_id_fkey(id, full_name, avatar_url)',
        { count: 'exact' }
      )
      .in('author_id', followingIds)
      .order('created_at', { ascending: false })
      .range(offset, offset + limit - 1);

    const formattedThreads = (threads || []).map((t: any) => ({
      id: t.id,
      title: t.title,
      body: t.body,
      vote_score: t.vote_score,
      upvotes: t.upvotes,
      reply_count: t.reply_count,
      view_count: t.view_count,
      created_at: t.created_at,
      author_id: t.author_id,
      author_name: t.user_profiles?.full_name || 'Unknown',
      author_avatar: t.user_profiles?.avatar_url,
      forum_categories: t.forum_categories,
    }));

    return NextResponse.json({
      threads: formattedThreads,
      total: count || 0,
      hasMore: (count || 0) > offset + limit,
    });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
