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

// GET /api/users/[id] - Get public user profile
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id: userId } = await params;

    // Get user with public information
    const user = await db.user.findUnique({
      where: { id: userId },
      select: {
        id: true,
        name: true,
        image: true,
        bio: true,
        role: true,
        university: true,
        semester: true,
        countryOfOrigin: true,
        createdAt: true,
        // Don't include email for privacy
      },
    });

    if (!user) {
      return NextResponse.json(
        { error: "User not found" },
        { status: 404 }
      );
    }

    // Calculate user statistics based on role
    let stats;

    if (user.role === "GUIDE") {
      // Guide statistics
      const [toursCreated, totalReviews, avgRatingData, activeBookings, tours, reviews] = await Promise.all([
        db.tour.count({
          where: {
            createdById: userId,
            published: true,
            archived: false,
          },
        }),
        db.review.count({
          where: {
            tour: {
              createdById: userId,
            },
          },
        }),
        db.tour.aggregate({
          where: {
            createdById: userId,
            published: true,
            archived: false,
            reviewCount: { gt: 0 },
          },
          _avg: {
            avgRating: true,
          },
        }),
        db.booking.count({
          where: {
            tour: {
              createdById: userId,
            },
            status: { in: ["PENDING", "CONFIRMED"] },
          },
        }),
        // Fetch guide's tours
        db.tour.findMany({
          where: {
            createdById: userId,
            published: true,
            archived: false,
          },
          select: {
            id: true,
            title: true,
            slug: true,
            description: true,
            city: true,
            priceCents: true,
            durationMin: true,
            maxGuests: true,
            avgRating: true,
            reviewCount: true,
            images: {
              select: {
                url: true,
              },
              take: 1,
              orderBy: {
                order: 'asc',
              },
            },
          },
          orderBy: {
            createdAt: 'desc',
          },
          take: 6,
        }),
        // Fetch reviews for guide's tours
        db.review.findMany({
          where: {
            tour: {
              createdById: userId,
            },
          },
          select: {
            id: true,
            rating: true,
            comment: true,
            createdAt: true,
            user: {
              select: {
                name: true,
                image: true,
              },
            },
            tour: {
              select: {
                title: true,
              },
            },
          },
          orderBy: {
            createdAt: 'desc',
          },
          take: 10,
        }),
      ]);

      stats = {
        toursCreated,
        totalReviews,
        avgRating: avgRatingData._avg.avgRating || 0,
        activeBookings,
        tours,
        reviews,
      };
    } else {
      // Explorer statistics
      const [bookingsCompleted, reviewsWritten, upcomingBookings] = await Promise.all([
        db.booking.count({
          where: {
            userId: userId,
            status: "COMPLETED",
          },
        }),
        db.review.count({
          where: {
            userId: userId,
          },
        }),
        db.booking.count({
          where: {
            userId: userId,
            status: { in: ["PENDING", "CONFIRMED"] },
          },
        }),
      ]);

      stats = {
        bookingsCompleted,
        reviewsWritten,
        upcomingBookings,
      };
    }

    return NextResponse.json({
      user,
      stats,
    });
  } catch (error) {
    console.error("Error fetching user profile:", error);
    return NextResponse.json(
      { error: "Failed to fetch user profile" },
      { status: 500 }
    );
  }
}
