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

export const runtime = 'nodejs'

export async function POST(request: Request) {
  try {
    const { userId } = await request.json()

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

    // Use raw query to avoid Prisma client sync issues
    const users = await prisma.$queryRaw`
      SELECT id, email, name, role, theme, "fontSize", "createdAt", "updatedAt", "lastLoginAt"
      FROM "User"
      WHERE id = ${userId}
    `
    const user = Array.isArray(users) && users.length > 0 ? users[0] : null

    // Also get a count of all users
    const userCount = await prisma.user.count()

    // Get all user IDs for comparison
    const allUsers = await prisma.user.findMany({
      select: { id: true, email: true, createdAt: true },
      orderBy: { createdAt: 'desc' },
      take: 5
    })

    return NextResponse.json({
      searchedUserId: userId,
      userExists: !!user,
      user: user || null,
      totalUsers: userCount,
      recentUsers: allUsers
    })
  } catch (error) {
    console.error('User debug error:', error)
    return NextResponse.json({ error: 'Debug failed', details: (error as any)?.message || error }, { status: 500 })
  }
}
