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

// GET /api/profile — Get user profile
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = request.nextUrl
    const userId = searchParams.get('userId') || ''

    if (!userId) {
      return NextResponse.json({ error: 'userId is required' }, { status: 400 })
    }

    const user = await db.user.findUnique({
      where: { id: userId },
      select: {
        id: true,
        email: true,
        firstName: true,
        lastName: true,
        phone: true,
        grade: true,
        gender: true,
        dateOfBirth: true,
        province: true,
        city: true,
        suburb: true,
        schoolName: true,
        role: true,
        status: true,
        points: true,
        profilePic: true,
        assessmentCompleted: true,
        howHeard: true,
        careerInterests: true,
        subjectsStruggling: true,
        createdAt: true,
        userPremium: {
          select: {
            id: true,
            plan: true,
            startDate: true,
            expiryDate: true,
          },
        },
        _count: {
          select: {
            academicResults: true,
            chatMessages: true,
            tutorSessionsLearner: true,
          },
        },
      },
    })

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

    return NextResponse.json({ user })
  } catch (error) {
    console.error('Error fetching profile:', error)
    return NextResponse.json({ error: 'Failed to fetch profile' }, { status: 500 })
  }
}

// PUT /api/profile — Update user profile
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json()
    const { userId, firstName, lastName, phone, province, city, suburb, schoolName } = body

    if (!userId) {
      return NextResponse.json({ error: 'userId is required' }, { status: 400 })
    }

    const updateData: Record<string, unknown> = {}
    if (firstName !== undefined) updateData.firstName = firstName
    if (lastName !== undefined) updateData.lastName = lastName
    if (phone !== undefined) updateData.phone = phone
    if (province !== undefined) updateData.province = province
    if (city !== undefined) updateData.city = city
    if (suburb !== undefined) updateData.suburb = suburb
    if (schoolName !== undefined) updateData.schoolName = schoolName

    const user = await db.user.update({
      where: { id: userId },
      data: updateData,
      select: {
        id: true,
        email: true,
        firstName: true,
        lastName: true,
        phone: true,
        province: true,
        city: true,
        suburb: true,
        schoolName: true,
      },
    })

    return NextResponse.json({ user, message: 'Profile updated successfully' })
  } catch (error) {
    console.error('Error updating profile:', error)
    return NextResponse.json({ error: 'Failed to update profile' }, { status: 500 })
  }
}
