import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { eventFeedbackService } from "@/services/events/event-feedback.service";
import {
  ValidationError,
  NotFoundError,
} from "@/services/errors";

export async function POST(
  request: Request,
  { params }: { params: Promise<{ eventId: string }> }
) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
    }

    const { eventId } = await params;
    const body = await request.json();
    const { rating, comment } = body;

    const feedback = await eventFeedbackService.validateAndCreateFeedback(
      session.user.id,
      eventId,
      { rating, comment }
    );

    return NextResponse.json({ success: true, feedback });
  } catch (error) {
    console.error("Error saving feedback:", error);
    
    if (error instanceof ValidationError) {
      return NextResponse.json({ error: error.message }, { status: 400 });
    }
    if (error instanceof NotFoundError) {
      return NextResponse.json({ error: error.message }, { status: 404 });
    }
    
    return NextResponse.json(
      { error: "Erreur lors de l'enregistrement du feedback" },
      { status: 500 }
    );
  }
}

export async function GET(
  request: Request,
  { params }: { params: Promise<{ eventId: string }> }
) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
    }

    const { eventId } = await params;

    // Récupérer le feedback de l'utilisateur pour cet événement
    const feedback = await eventFeedbackService.getUserFeedback(
      session.user.id,
      eventId
    );

    return NextResponse.json({ feedback });
  } catch (error) {
    console.error("Error fetching feedback:", error);
    return NextResponse.json(
      { error: "Erreur lors de la récupération du feedback" },
      { status: 500 }
    );
  }
}
