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

// Validation schema for rating submission
const ratingSchema = z.object({
  match_id: z.string().uuid(),
  to_id: z.string().uuid(),
  score: z.number().int().min(1).max(5),
  comment: z.string().max(500).optional(),
});

export type RatingInput = z.infer<typeof ratingSchema>;

/**
 * POST /api/ratings
 * Submit a new rating for a worker or contractor
 */
export async function POST(request: NextRequest) {
  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 });
    }

    // Parse and validate request body
    const body = await request.json();
    const validation = ratingSchema.safeParse(body);
    
    if (!validation.success) {
      return NextResponse.json(
        { error: "Invalid input", details: validation.error.flatten() },
        { status: 400 }
      );
    }

    const { match_id, to_id, score, comment } = validation.data;

    // Verify the match exists and the user is a participant
    const { data: match, error: matchError } = await supabase
      .from('matches')
      .select('id, job_id, worker_id, status')
      .eq('id', match_id)
      .or(`worker_id.eq.${user.id},job_id.in.(select id from jobs where company_id.eq.${user.id})`)
      .single();

    if (matchError || !match) {
      return NextResponse.json(
        { error: "Match not found or you are not a participant" },
        { status: 404 }
      );
    }

    // Only allow ratings for completed matches
    if (match.status !== 'completed') {
      return NextResponse.json(
        { error: "Can only rate completed jobs" },
        { status: 400 }
      );
    }

    // Check if user has already rated this match
    const { data: existingRating, error: existingError } = await supabase
      .from('ratings')
      .select('id')
      .eq('match_id', match_id)
      .eq('from_id', user.id)
      .single();

    if (existingRating) {
      return NextResponse.json(
        { error: "You have already rated this match" },
        { status: 409 }
      );
    }

    // Insert the rating
    const { data: rating, error: ratingError } = await supabase
      .from('ratings')
      .insert({
        match_id,
        from_id: user.id,
        to_id,
        score,
        comment: comment || null,
      })
      .select('id, score, comment, created_at')
      .single();

    if (ratingError) {
      console.error("Error creating rating:", ratingError);
      return NextResponse.json(
        { error: "Failed to submit rating" },
        { status: 500 }
      );
    }

    // Create notification for the rated user
    const { data: fromProfile } = await supabase
      .from('profiles')
      .select('name')
      .eq('id', user.id)
      .single();

    const { error: notifError } = await supabase
      .from('notifications')
      .insert({
        profile_id: to_id,
        type: 'system',
        title: 'New Rating Received',
        body: `${fromProfile?.name || 'Someone'} left you a ${score}-star rating`,
        data: {
          rating_id: rating.id,
          score,
          match_id,
        },
      });

    if (notifError) {
      console.error('Failed to create rating notification:', notifError);
    }

    return NextResponse.json({
      success: true,
      rating: {
        id: rating.id,
        score: rating.score,
        comment: rating.comment,
        created_at: rating.created_at,
      },
    });
  } catch (error) {
    console.error("Error in ratings API:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
