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

/**
 * GET /api/ratings/[userId]
 * Get all ratings for a specific user with aggregation
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ userId: string }> }
) {
  try {
    const supabase = await createClient();
    const { userId } = await params;

    // Check if user is authenticated
    const { data: { user }, error: authError } = await supabase.auth.getUser();
    
    if (authError || !user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Get URL params for pagination
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');
    const offset = (page - 1) * limit;

    // Get aggregated rating statistics
    const { data: stats, error: statsError } = await supabase
      .from('ratings')
      .select('score')
      .eq('to_id', userId);

    if (statsError) {
      console.error("Error fetching rating stats:", statsError);
      return NextResponse.json(
        { error: "Failed to fetch ratings" },
        { status: 500 }
      );
    }

    // Calculate statistics
    const totalRatings = stats?.length || 0;
    const averageRating = totalRatings > 0
      ? stats.reduce((acc, r) => acc + r.score, 0) / totalRatings
      : 0;

    // Distribution of ratings
    const distribution = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };
    stats?.forEach(r => {
      distribution[r.score as keyof typeof distribution]++;
    });

    // Get paginated ratings with reviewer info
    const { data: ratings, error: ratingsError } = await supabase
      .from('ratings')
      .select(`
        id,
        score,
        comment,
        created_at,
        from:profiles!ratings_from_id_fkey(name, type)
      `)
      .eq('to_id', userId)
      .order('created_at', { ascending: false })
      .range(offset, offset + limit - 1);

    if (ratingsError) {
      console.error("Error fetching ratings:", ratingsError);
      return NextResponse.json(
        { error: "Failed to fetch ratings" },
        { status: 500 }
      );
    }

    // Get total count for pagination
    const { count, error: countError } = await supabase
      .from('ratings')
      .select('*', { count: 'exact', head: true })
      .eq('to_id', userId);

    if (countError) {
      console.error("Error counting ratings:", countError);
    }

    return NextResponse.json({
      summary: {
        average_rating: Number(averageRating.toFixed(1)),
        total_ratings: totalRatings,
        distribution,
      },
      ratings: ratings?.map(r => ({
        id: r.id,
        score: r.score,
        comment: r.comment,
        created_at: r.created_at,
        reviewer: Array.isArray(r.from) ? r.from[0] : r.from,
      })) || [],
      pagination: {
        page,
        limit,
        total: count || totalRatings,
        has_more: (offset + limit) < (count || totalRatings),
      },
    });
  } catch (error) {
    console.error("Error in get ratings API:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
