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

// GET /api/tutors — List tutors with filters
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = request.nextUrl
    const subject = searchParams.get('subject') || ''
    const province = searchParams.get('province') || ''
    const city = searchParams.get('city') || ''
    const serviceType = searchParams.get('serviceType') || ''
    const minRating = parseFloat(searchParams.get('minRating') || '0')
    const priceMin = parseFloat(searchParams.get('priceMin') || '0')
    const priceMax = parseFloat(searchParams.get('priceMax') || '99999')
    const sort = searchParams.get('sort') || 'rating' // rating, price_asc, price_desc, sessions

    // Build where clause
    const where: Record<string, unknown> = {}

    if (province) where.province = province
    if (city) where.city = city
    if (serviceType) where.serviceType = serviceType
    if (minRating > 0) where.rating = { gte: minRating }
    if (priceMin > 0 || priceMax < 99999) {
      const rateFilter: Record<string, unknown> = {}
      if (priceMin > 0) rateFilter.gte = priceMin
      if (priceMax < 99999) rateFilter.lte = priceMax
      where.hourlyRate = rateFilter
    }

    // Subject filter (JSON array contains)
    if (subject) {
      where.subjects = { contains: subject }
    }

    // Sort
    let orderBy: Record<string, string> = { rating: 'desc' }
    if (sort === 'price_asc') orderBy = { hourlyRate: 'asc' }
    else if (sort === 'price_desc') orderBy = { hourlyRate: 'desc' }
    else if (sort === 'sessions') orderBy = { totalSessions: 'desc' }

    const tutors = await db.tutorProfile.findMany({
      where,
      include: {
        user: {
          select: {
            id: true,
            firstName: true,
            lastName: true,
            email: true,
            profilePic: true,
            province: true,
            city: true,
          },
        },
      },
      orderBy,
    })

    // Parse JSON fields
    const formattedTutors = tutors.map((t) => ({
      id: t.id,
      userId: t.userId,
      bio: t.bio,
      subjects: JSON.parse(t.subjects || '[]'),
      hourlyRate: t.hourlyRate,
      rating: t.rating,
      totalSessions: t.totalSessions,
      province: t.province,
      city: t.city,
      serviceType: t.serviceType,
      qualifications: JSON.parse(t.qualifications || '[]'),
      experience: t.experience,
      createdAt: t.createdAt,
      user: t.user,
    }))

    return NextResponse.json({ tutors: formattedTutors, count: formattedTutors.length })
  } catch (error) {
    console.error('Error fetching tutors:', error)
    return NextResponse.json({ error: 'Failed to fetch tutors' }, { status: 500 })
  }
}
