import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    // Fetch dynamic ratings first
    let dynamicRating = 0;
    let reviewCount = 0;

    try {
      // Get user ID from email
      const user = await prisma.user.findUnique({
        where: { email: session.user.email },
        select: { id: true }
      });

      if (user) {
        // Fetch all reviews where this user is the recipient (client being reviewed)
        const reviews = await prisma.review.findMany({
          where: {
            recipientId: user.id
          },
          select: {
            rating: true
          }
        });

        reviewCount = reviews.length;

        if (reviewCount > 0) {
          const totalRating = reviews.reduce((sum, review) => sum + review.rating, 0);
          dynamicRating = Math.round((totalRating / reviewCount) * 10) / 10;
        }
      }
    } catch (dbError) {
      console.log('Database not available, using fallback ratings');
      // Keep default values
    }

    // Get actual user profile data from database
    let profileData = null;

    try {
      // Get user with profile data from database
      const user = await prisma.user.findUnique({
        where: { email: session.user.email },
        include: {
          profile: {
            include: {
              country: true
            }
          }
        }
      });

      if (user && user.profile) {
        // Calculate profile completion percentage
        const profile = user.profile;
        const fields = [
          profile.firstName,
          profile.lastName,
          profile.phone,
          profile.city,
          profile.bio
        ];
        const filledFields = fields.filter(field => field && field.toString().trim() !== '').length;
        const profileCompletion = Math.round((filledFields / fields.length) * 100);

        // Use actual profile data from database
        profileData = {
          id: user.id,
          firstName: profile.firstName,
          lastName: profile.lastName,
          email: user.email,
          phone: profile.phone,
          country: profile.countryId,
          city: profile.city,
          profileImage: user.image || '/assets/image/profile03.png',
          rating: dynamicRating,
          reviewCount: reviewCount,
          profileCompletion: profileCompletion,
          bio: profile.bio,
          createdAt: user.createdAt.toISOString(),
          updatedAt: user.updatedAt.toISOString()
        };
      }
    } catch (dbError) {
      console.error('Database error:', dbError);
      return NextResponse.json(
        {
          error: 'Database connection failed',
          type: 'database_error'
        },
        { status: 503 }
      );
    }

    if (!profileData) {
      return NextResponse.json(
        {
          error: 'Profile not found. Please complete your profile setup.',
          type: 'profile_not_found'
        },
        { status: 404 }
      );
    }

    return NextResponse.json({
      success: true,
      data: profileData
    });

  } catch (error) {
    console.error('Error fetching client profile:', error);
    return NextResponse.json(
      {
        error: error instanceof Error ? error.message : 'Failed to fetch profile',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}