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

/**
 * GET /api/ratings/pending
 * Get pending ratings for the current user (jobs they need to rate)
 */
export async function GET() {
  try {
    const supabase = await createClient();

    // 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 user's profile type
    const { data: profile, error: profileError } = await supabase
      .from('profiles')
      .select('type')
      .eq('id', user.id)
      .single();

    if (profileError || !profile) {
      return NextResponse.json(
        { error: "Profile not found" },
        { status: 404 }
      );
    }

    // Get completed matches where user hasn't rated the other party yet
    let query = supabase
      .from('matches')
      .select(`
        id,
        status,
        completed_at,
        job:jobs(id, title, trade),
        worker:profiles!matches_worker_id_fkey(id, name, avatar_url),
        company:companies(name)
      `)
      .eq('status', 'completed');

    if (profile.type === 'worker') {
      // Worker: get matches where worker is the user and they haven't rated the company
      query = query.eq('worker_id', user.id);
    } else {
      // Contractor: get matches where job was posted by user's company and they haven't rated the worker
      query = query.filter('job_id', 'in', 
        supabase.from('jobs').select('id').eq('company_id', user.id)
      );
    }

    const { data: matches, error: matchesError } = await query;

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

    // Filter out matches that already have ratings from this user
    const { data: existingRatings, error: ratingsError } = await supabase
      .from('ratings')
      .select('match_id')
      .eq('from_id', user.id);

    if (ratingsError) {
      console.error("Error fetching existing ratings:", ratingsError);
    }

    const ratedMatchIds = new Set(existingRatings?.map(r => r.match_id) || []);
    
    // Filter matches and format response
    const pendingRatings = matches
      ?.filter(m => !ratedMatchIds.has(m.id))
      .map(m => ({
        match_id: m.id,
        job: m.job,
        completed_at: m.completed_at,
        ratee: profile.type === 'worker' 
          ? { id: m.job?.company_id, name: m.company?.name, type: 'contractor' }
          : { id: m.worker?.id, name: m.worker?.name, type: 'worker', avatar_url: m.worker?.avatar_url },
      })) || [];

    return NextResponse.json({
      pending: pendingRatings,
      count: pendingRatings.length,
    });
  } catch (error) {
    console.error("Error in pending ratings API:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
