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

// GET /api/forum/follows?user_id=xxx&viewer_id=yyy
// Returns follower count, following count, and whether viewer follows user
export async function GET(req: NextRequest) {
  try {
    const supabase = await createClient();
    const { searchParams } = new URL(req.url);
    const userId = searchParams.get('user_id');
    const viewerId = searchParams.get('viewer_id');

    if (!userId) {
      return NextResponse.json({ error: 'user_id is required' }, { status: 400 });
    }

    // Follower count (people who follow this user)
    const { count: followerCount } = await supabase
      .from('user_follows')
      .select('*', { count: 'exact', head: true })
      .eq('following_id', userId);

    // Following count (people this user follows)
    const { count: followingCount } = await supabase
      .from('user_follows')
      .select('*', { count: 'exact', head: true })
      .eq('follower_id', userId);

    // Whether the viewer follows this user
    let isFollowing = false;
    if (viewerId && viewerId !== userId) {
      const { data: followRow } = await supabase
        .from('user_follows')
        .select('id')
        .eq('follower_id', viewerId)
        .eq('following_id', userId)
        .maybeSingle();
      isFollowing = !!followRow;
    }

    // Fetch followers list (people who follow this user)
    const { data: followers } = await supabase
      .from('user_follows')
      .select('follower_id, created_at, user_profiles!user_follows_follower_id_fkey(id, full_name, avatar_url, reputation)')
      .eq('following_id', userId)
      .order('created_at', { ascending: false })
      .limit(50);

    // Fetch following list (people this user follows)
    const { data: following } = await supabase
      .from('user_follows')
      .select('following_id, created_at, user_profiles!user_follows_following_id_fkey(id, full_name, avatar_url, reputation)')
      .eq('follower_id', userId)
      .order('created_at', { ascending: false })
      .limit(50);

    return NextResponse.json({
      followerCount: followerCount || 0,
      followingCount: followingCount || 0,
      isFollowing,
      followers: (followers || []).map((f: any) => ({
        id: f.user_profiles?.id,
        full_name: f.user_profiles?.full_name,
        avatar_url: f.user_profiles?.avatar_url,
        reputation: f.user_profiles?.reputation,
        followed_at: f.created_at,
      })),
      following: (following || []).map((f: any) => ({
        id: f.user_profiles?.id,
        full_name: f.user_profiles?.full_name,
        avatar_url: f.user_profiles?.avatar_url,
        reputation: f.user_profiles?.reputation,
        followed_at: f.created_at,
      })),
    });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}

// POST /api/forum/follows — follow a user
export async function POST(req: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await req.json();
    const { following_id } = body;

    if (!following_id) {
      return NextResponse.json({ error: 'following_id is required' }, { status: 400 });
    }
    if (following_id === user.id) {
      return NextResponse.json({ error: 'Cannot follow yourself' }, { status: 400 });
    }

    const { error } = await supabase
      .from('user_follows')
      .insert({ follower_id: user.id, following_id });

    if (error) {
      if (error.code === '23505') {
        return NextResponse.json({ message: 'Already following' }, { status: 200 });
      }
      throw error;
    }

    return NextResponse.json({ message: 'Followed successfully' }, { status: 201 });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}

// DELETE /api/forum/follows — unfollow a user
export async function DELETE(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 followingId = searchParams.get('following_id');

    if (!followingId) {
      return NextResponse.json({ error: 'following_id is required' }, { status: 400 });
    }

    await supabase
      .from('user_follows')
      .delete()
      .eq('follower_id', user.id)
      .eq('following_id', followingId);

    return NextResponse.json({ message: 'Unfollowed successfully' });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
