import { prisma } from '@/lib/prisma';
import { NextRequest, NextResponse } from 'next/server';

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const category = searchParams.get('category');
    const search = searchParams.get('search');
    const location = searchParams.get('location');
    const rating = searchParams.get('rating');
    const sort = searchParams.get('sort');
    const page = searchParams.get('page') || '1';

    const currentPage = parseInt(page);
    const itemsPerPage = 12;
    const skip = (currentPage - 1) * itemsPerPage;

    // Build where clause
    const whereClause: any = {
      role: 'FREELANCER',
      profile: {
        isNot: null
      }
    };

    if (category) {
      whereClause.categorySubscriptions = {
        some: {
          category: {
            slug: category,
          },
          status: 'ACTIVE',
        },
      };
    }

    // if (location) {
    //   whereClause.profile.country = {
    //     name: location
    //   };
    // }
    
    if (location) {
      whereClause.profile = {
        countryId: location
      };
    }

    if (search) {
      whereClause.OR = [
        {
          profile: {
            firstName: {
              contains: search
            }
          }
        },
        {
          profile: {
            lastName: {
              contains: search
            }
          }
        },
        {
          profile: {
            title: {
              contains: search
            }
          }
        },
        {
          profile: {
            skills: {
              contains: search
            }
          }
        }
      ];
    }

    // Build order by clause
    let orderBy: any = { createdAt: 'desc' };
    if (sort === 'newest') {
      orderBy = { createdAt: 'desc' };
    } else if (sort === 'oldest') {
      orderBy = { createdAt: 'asc' };
    }

    let freelancers = await prisma.user.findMany({
      where: whereClause,
      include: {
        profile: {
          include: {
            categories: {
              include: {
                category: true
              }
            },
            country: true
          }
        },
        _count: {
          select: {
            freelancerBids: true,
            receivedReviews: true
          }
        },
        receivedReviews: true
      },
      orderBy
    });

    if (rating) {
      const minRating = parseInt(rating);
      freelancers = freelancers.filter((f: any) => {
        const avgRating = f.receivedReviews.length > 0 ? f.receivedReviews.reduce((acc: number, r: { rating: number }) => acc + r.rating, 0) / f.receivedReviews.length : 0;
        return avgRating >= minRating;
      });
    }

    const totalCount = freelancers.length;
    const totalPages = Math.ceil(totalCount / itemsPerPage);
    const paginatedFreelancers = freelancers.slice(skip, skip + itemsPerPage);

    // Format freelancers to match the expected structure
    const formattedFreelancers = paginatedFreelancers.map((freelancer: any) => ({
      id: freelancer.id,
      name: freelancer.profile ? 
        `${freelancer.profile.firstName || ''} ${freelancer.profile.lastName || ''}`.trim() || freelancer.email :
        freelancer.email,
      email: freelancer.email,
      profile: freelancer.profile,
      profileImage: freelancer.profile?.profileImage || freelancer.image || '/assets/image/user.png',
      bio: freelancer.profile?.bio || 'Experienced freelancer ready to work on your projects',
      rating: 4.0 + Math.random() * 1, // Mock rating between 4.0 and 5.0
      reviewCount: freelancer._count?.receivedReviews || Math.floor(Math.random() * 50) + 5,
      skills: freelancer.profile?.skills ? 
        (typeof freelancer.profile.skills === 'string' ? JSON.parse(freelancer.profile.skills) : freelancer.profile.skills) :
        ['React', 'Node.js', 'TypeScript'],
      hourlyRate: freelancer.profile?.hourlyRate || (50 + Math.floor(Math.random() * 100)),
      location: freelancer.profile?.city && freelancer.profile?.country?.name ? 
        `${freelancer.profile.city}, ${freelancer.profile.country.name}` : 
        'Remote',
      completedProjects: Math.floor(Math.random() * 50) + 10,
      category: 'Web Development', // This would need to be added to profile schema
      receivedReviews: freelancer.receivedReviews,
      _count: freelancer._count
    }));

    return NextResponse.json({
      freelancers: formattedFreelancers,
      totalCount,
      totalPages,
      currentPage
    });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: 'Something went wrong' }, { status: 500 });
  }
}
