import { NextResponse } from 'next/server'
import { getUserFromToken } from '@/lib/auth'

export const runtime = 'nodejs'

function getErrorMessages(locale: string = 'ro') {
  const messages = {
    ro: {
      tokenRequired: 'Token de autentificare necesar',
      invalidToken: 'Token invalid',
      serverError: 'Eroare de server'
    },
    en: {
      tokenRequired: 'Authentication token required',
      invalidToken: 'Invalid token',
      serverError: 'Server error'
    }
  }
  return messages[locale as keyof typeof messages] || messages.ro
}

export async function GET(request: Request) {
  try {
    const url = new URL(request.url)
    const locale = url.searchParams.get('locale') || 'ro'
    const messages = getErrorMessages(locale)

    const authHeader = request.headers.get('authorization')
    const token = authHeader?.replace('Bearer ', '')

    if (!token) {
      return NextResponse.json({ error: messages.tokenRequired }, { status: 401 })
    }

    const user = await getUserFromToken(token)
    if (!user) {
      return NextResponse.json({ error: messages.invalidToken }, { status: 401 })
    }

    return NextResponse.json({ user })
  } catch (error) {
    console.error('User validation error:', error)
    const url = new URL(request.url)
    const locale = url.searchParams.get('locale') || 'ro'
    const messages = getErrorMessages(locale)
    return NextResponse.json({ error: messages.serverError }, { status: 500 })
  }
}
