import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { getMaxVersionLimit } from '@/lib/subscription'

// GET /api/users/profile - 获取用户配置
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')

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

    const user = await prisma.user.findUnique({
      where: { id: userId },
      select: {
        id: true,
        email: true,
        username: true,
        avatar: true,
        bio: true,
        language: true,
        versionLimit: true,
        subscribePlan: true,
        maxVersionLimit: true,
        promptLimit: true,
        creditBalance: true,
        createdAt: true,
        updatedAt: true
      }
    })

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

    return NextResponse.json(user)

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

// PUT /api/users/profile - 更新用户配置
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json()
    const { 
      userId, 
      username, 
      avatar, 
      bio, 
      language, 
      versionLimit 
    } = body

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

    // 获取用户当前信息以验证版本限制
    const currentUser = await prisma.user.findUnique({
      where: { id: userId },
      select: { subscribePlan: true, maxVersionLimit: true }
    })

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

    // 验证版本限制不能超过订阅计划的最大限制
    let finalVersionLimit = versionLimit
    if (versionLimit !== undefined) {
      const maxVersionLimit = getMaxVersionLimit(currentUser.subscribePlan)
      if (versionLimit > maxVersionLimit) {
        return NextResponse.json(
          { 
            error: 'Version limit exceeds subscription plan maximum',
            maxAllowed: maxVersionLimit
          },
          { status: 400 }
        )
      }
      finalVersionLimit = Math.max(1, Math.min(versionLimit, maxVersionLimit))
    }

    const updateData: Record<string, unknown> = {}
    if (username !== undefined) updateData.username = username
    if (avatar !== undefined) updateData.avatar = avatar
    if (bio !== undefined) updateData.bio = bio
    if (language !== undefined) updateData.language = language
    if (finalVersionLimit !== undefined) updateData.versionLimit = finalVersionLimit

    const updatedUser = await prisma.user.update({
      where: { id: userId },
      data: updateData,
      select: {
        id: true,
        email: true,
        username: true,
        avatar: true,
        bio: true,
        language: true,
        versionLimit: true,
        subscribePlan: true,
        maxVersionLimit: true,
        promptLimit: true,
        creditBalance: true,
        createdAt: true,
        updatedAt: true
      }
    })

    return NextResponse.json(updatedUser)

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