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 = 4.5;
    let reviewCount = 25;
    
    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 (freelancer 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.zipCode,
          profile.bio,
          profile.hourlyRate
        ];
        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,
          zipCode: profile.zipCode,
          profileImage: user.image || '/assets/image/profile03.png',
          rating: dynamicRating,
          reviewCount: reviewCount,
          profileCompletion: profileCompletion,
          bio: profile.bio,
          hourlyRate: profile.hourlyRate,
          availability: 'AVAILABLE',
          skills: [],
          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 freelancer profile:', error);
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to fetch profile',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}

export async function PUT(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const body = await req.json();
    const { 
      firstName, 
      lastName, 
      email, 
      phone, 
      country, 
      city, 
      zipCode,
      bio,
      hourlyRate,
      availability,
      skills
    } = body;

    // Debug logging
    console.log('Profile update data received:', {
      firstName,
      lastName,
      email,
      phone,
      country,
      city,
      zipCode,
      bio
    });

    // Validate required fields
    if (!firstName || !lastName || !email) {
      return NextResponse.json(
        { error: 'First name, last name, and email are required' },
        { status: 400 }
      );
    }

    // 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, image: true }
      });

      if (user) {
        // Fetch all reviews where this user is the recipient (freelancer 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
    }

    // Update actual profile data in database
    let updatedProfileData = null;

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

      if (user) {
        // Update or create profile
        const updatedProfile = await prisma.profile.upsert({
          where: { userId: user.id },
          update: {
            firstName: firstName,
            lastName: lastName,
            phone: phone,
            countryId: country,
            city: city,
            bio: bio,
            zipCode: zipCode || '',
            hourlyRate: hourlyRate ? parseFloat(hourlyRate.toString()) : null,
          },
          create: {
            userId: user.id,
            firstName: firstName,
            lastName: lastName,
            phone: phone,
            countryId: country || 'switzerland',
            city: city,
            bio: bio,
            zipCode: zipCode || '',
            hourlyRate: hourlyRate ? parseFloat(hourlyRate.toString()) : null,
          },
          include: {
            country: true
          }
        });

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

        // Use actual updated profile data
        updatedProfileData = {
          id: user.id,
          firstName: updatedProfile.firstName,
          lastName: updatedProfile.lastName,
          email: email,
          phone: updatedProfile.phone,
          country: updatedProfile.countryId,
          city: updatedProfile.city,
          profileImage: user.image || '/assets/image/profile03.png',
          rating: dynamicRating,
          reviewCount: reviewCount,
          profileCompletion: profileCompletion,
          bio: updatedProfile.bio,
          hourlyRate: updatedProfile.hourlyRate,
          availability: availability || 'AVAILABLE',
          skills: skills || []
        };
      }
    } catch (dbError) {
      console.error('Database error during profile update:', dbError);
      return NextResponse.json(
        {
          error: 'Failed to update profile',
          type: 'database_error'
        },
        { status: 503 }
      );
    }

    if (!updatedProfileData) {
      return NextResponse.json(
        {
          error: 'Failed to update profile',
          type: 'update_failed'
        },
        { status: 500 }
      );
    }

    return NextResponse.json({
      success: true,
      data: updatedProfileData,
      message: 'Profile updated successfully'
    });

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