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

export const runtime = 'nodejs'

// Get user's favorite Bible version
export async function GET(request: Request) {
  try {
    const authHeader = request.headers.get('authorization')
    if (!authHeader?.startsWith('Bearer ')) {
      return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
    }

    const token = authHeader.substring(7)
    const decoded = jwt.verify(token, process.env.JWT_SECRET!) as { userId: string }

    const user = await prisma.user.findUnique({
      where: { id: decoded.userId },
      select: { favoriteBibleVersion: true }
    })

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

    return NextResponse.json({
      success: true,
      favoriteBibleVersion: user.favoriteBibleVersion
    })
  } catch (error) {
    console.error('Error getting favorite version:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to get favorite version' },
      { status: 500 }
    )
  }
}

// Set user's favorite Bible version
export async function POST(request: Request) {
  try {
    const authHeader = request.headers.get('authorization')
    if (!authHeader?.startsWith('Bearer ')) {
      return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
    }

    const token = authHeader.substring(7)
    const decoded = jwt.verify(token, process.env.JWT_SECRET!) as { userId: string }

    const body = await request.json()
    const { versionId } = body

    if (!versionId) {
      return NextResponse.json({ success: false, error: 'Version ID is required' }, { status: 400 })
    }

    // Verify that the version exists
    const version = await prisma.bibleVersion.findUnique({
      where: { id: versionId }
    })

    if (!version) {
      return NextResponse.json({ success: false, error: 'Bible version not found' }, { status: 404 })
    }

    // Update user's favorite version
    await prisma.user.update({
      where: { id: decoded.userId },
      data: { favoriteBibleVersion: versionId }
    })

    return NextResponse.json({
      success: true,
      message: 'Favorite Bible version updated',
      favoriteBibleVersion: versionId
    })
  } catch (error) {
    console.error('Error setting favorite version:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to set favorite version' },
      { status: 500 }
    )
  }
}