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

// GET /api/tutors/[id] — Get single tutor details
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params

    const tutor = await db.tutorProfile.findUnique({
      where: { id },
      include: {
        user: {
          select: {
            id: true,
            firstName: true,
            lastName: true,
            email: true,
            phone: true,
            profilePic: true,
            province: true,
            city: true,
            schoolName: true,
          },
        },
      },
    })

    if (!tutor) {
      return NextResponse.json({ error: 'Tutor not found' }, { status: 404 })
    }

    return NextResponse.json({
      tutor: {
        id: tutor.id,
        userId: tutor.userId,
        bio: tutor.bio,
        subjects: JSON.parse(tutor.subjects || '[]'),
        hourlyRate: tutor.hourlyRate,
        rating: tutor.rating,
        totalSessions: tutor.totalSessions,
        province: tutor.province,
        city: tutor.city,
        serviceType: tutor.serviceType,
        subscriptionStatus: tutor.subscriptionStatus,
        qualifications: JSON.parse(tutor.qualifications || '[]'),
        experience: tutor.experience,
        createdAt: tutor.createdAt,
        user: tutor.user,
      },
    })
  } catch (error) {
    console.error('Error fetching tutor:', error)
    return NextResponse.json({ error: 'Failed to fetch tutor' }, { status: 500 })
  }
}

// POST /api/tutors/[id] — Book a session
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const body = await request.json()
    const { learnerId, subject, dateTime, duration, notes } = body

    if (!learnerId || !subject || !dateTime) {
      return NextResponse.json(
        { error: 'Missing required fields: learnerId, subject, dateTime' },
        { status: 400 }
      )
    }

    // Verify tutor exists
    const tutor = await db.tutorProfile.findUnique({ where: { id } })
    if (!tutor) {
      return NextResponse.json({ error: 'Tutor not found' }, { status: 404 })
    }

    const session = await db.tutorSession.create({
      data: {
        tutorId: tutor.userId,
        learnerId,
        subject,
        dateTime: new Date(dateTime),
        duration: duration || 60,
        rate: tutor.hourlyRate,
        notes,
        status: 'booked',
      },
    })

    return NextResponse.json({ session, message: 'Session booked successfully' })
  } catch (error) {
    console.error('Error booking session:', error)
    return NextResponse.json({ error: 'Failed to book session' }, { status: 500 })
  }
}
