import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { OpenRouterService } from '@/lib/openrouter'
import { ReplicateService } from '@/lib/replicate'
import { UniAPIService } from '@/lib/uniapi'
import { FalService } from '@/lib/fal'

// GET /api/admin/models - 获取所有模型
export async function GET() {
  try {
    const models = await prisma.model.findMany({
      include: {
        subscriptionPlan: {
          select: {
            id: true,
            name: true,
            displayName: true
          }
        }
      },
      orderBy: [
        { provider: 'asc' },
        { name: 'asc' }
      ]
    })

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

// POST /api/admin/models - 同步和添加模型
export async function POST(request: NextRequest) {
  try {
    const { action, selectedModels, serviceProvider } = await request.json()

    if (action === 'sync') {

      const provider = serviceProvider || 'openrouter'
      let availableModels: Array<Record<string, unknown>> = []

      if (provider === 'openrouter') {
        // 从 OpenRouter 获取可用模型
        const openRouterService = new OpenRouterService()
        const openRouterModels = await openRouterService.getAvailableModels()
        availableModels = openRouterModels.map(model =>
          openRouterService.transformModelForDB(model)
        )
      } else if (provider === 'replicate') {
        // 从 Replicate 获取可用模型
        const replicateService = new ReplicateService()

        // 获取不同类型的模型
        const [imageModels, videoModels, audioModels] = await Promise.all([
          replicateService.getImageGenerationModels(),
          replicateService.getVideoGenerationModels(),
          replicateService.getAudioGenerationModels()
        ])

        // 转换为数据库格式
        const transformedImageModels = imageModels.map(model =>
          replicateService.transformModelForDB(model, 'image')
        )
        const transformedVideoModels = videoModels.map(model =>
          replicateService.transformModelForDB(model, 'video')
        )
        const transformedAudioModels = audioModels.map(model =>
          replicateService.transformModelForDB(model, 'audio')
        )

        availableModels = [
          ...transformedImageModels,
          ...transformedVideoModels,
          ...transformedAudioModels
        ]
      } else if (provider === 'uniapi') {
        // 从 UniAPI 获取可用模型
        const uniAPIService = new UniAPIService()
        const uniAPIModels = await uniAPIService.getAvailableModels()
        availableModels = uniAPIModels
          .map(model => uniAPIService.transformModelForDB(model))
          .filter(model => model !== null) // 过滤掉可能的 null 值
      } else if (provider === 'fal') {
        // 从 Fal.ai 获取可用模型
        const falService = new FalService()
        const falModels = await falService.getAvailableModels()
        availableModels = falModels
          .map(model => falService.transformModelForDB(model))
          .filter(model => model !== null) // 过滤掉可能的 null 值
      }

      return NextResponse.json({
        message: 'Models fetched successfully',
        availableModels,
        serviceProvider: provider
      })
    }

    if (action === 'add') {
      if (!selectedModels || !Array.isArray(selectedModels)) {
        return NextResponse.json(
          { error: 'Selected models are required' },
          { status: 400 }
        )
      }

      // 检查模型 ID 的全局唯一性
      const modelIds = selectedModels.map(model => model.modelId)
      const existingModels = await prisma.model.findMany({
        where: {
          modelId: {
            in: modelIds
          }
        },
        select: {
          modelId: true,
          serviceProvider: true,
          name: true
        }
      })

      if (existingModels.length > 0) {
        const conflicts = existingModels.map(model => ({
          modelId: model.modelId,
          existingServiceProvider: model.serviceProvider,
          modelName: model.name
        }))

        return NextResponse.json({
          error: 'Model ID conflicts detected',
          conflicts: conflicts,
          message: `The following model IDs already exist: ${conflicts.map(c => `${c.modelId} (${c.modelName} - ${c.existingServiceProvider})`).join(', ')}`
        }, { status: 409 })
      }

      // 批量创建模型记录 - 所有模型默认绑定到 free 套餐
      const results = []
      for (const modelData of selectedModels) {
        const result = await prisma.model.create({
          data: {
            ...modelData,
            subscriptionPlanId: 'free' // 默认绑定到 free 套餐，所有套餐都可使用
          },
          include: {
            subscriptionPlan: {
              select: {
                id: true,
                displayName: true
              }
            }
          }
        })
        
        results.push(result)
      }

      return NextResponse.json({ 
        message: `Successfully added ${results.length} models`,
        models: results
      })
    }

    return NextResponse.json(
      { error: 'Invalid action' },
      { status: 400 }
    )
  } catch (error) {
    console.error('Error handling models:', error)
    return NextResponse.json(
      { error: 'Failed to process models request' },
      { status: 500 }
    )
  }
}

// PUT /api/admin/models - 更新模型状态
export async function PUT(request: NextRequest) {
  try {
    const { modelId, isActive } = await request.json()

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

    const model = await prisma.model.update({
      where: { id: modelId },
      data: { isActive },
      include: {
        subscriptionPlan: true
      }
    })

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

// DELETE /api/admin/models - 删除模型
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const modelId = searchParams.get('id')

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

    await prisma.model.delete({
      where: { id: modelId }
    })

    return NextResponse.json({ message: 'Model deleted successfully' })
  } catch (error) {
    console.error('Error deleting model:', error)
    return NextResponse.json(
      { error: 'Failed to delete model' },
      { status: 500 }
    )
  }
}