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: [
        { subscriptionPlan: { sortOrder: 'asc' } },
        { 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, planId, selectedModels, serviceProvider } = await request.json()

    if (action === 'sync') {
      if (!planId) {
        return NextResponse.json(
          { error: 'Plan ID is required for sync action' },
          { status: 400 }
        )
      }

      // 验证套餐是否存在
      const plan = await prisma.subscriptionPlan.findUnique({
        where: { id: planId }
      })

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

      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,
        planId,
        serviceProvider: provider
      })
    }

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

      // 检查模型 ID 的唯一性
      const modelIds = selectedModels.map(model => model.modelId)
      const existingModels = await prisma.model.findMany({
        where: {
          modelId: {
            in: modelIds
          },
          subscriptionPlanId: {
            not: planId // 排除当前套餐，允许同一套餐内更新
          }
        },
        include: {
          subscriptionPlan: {
            select: {
              displayName: true
            }
          }
        }
      })

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

        return NextResponse.json({
          error: 'Model ID conflicts detected',
          conflicts: conflicts,
          message: `The following model IDs are already used by other service providers: ${conflicts.map(c => `${c.modelId} (used by ${c.existingServiceProvider} in ${c.existingPlan})`).join(', ')}`
        }, { status: 409 })
      }

      // 批量创建模型记录
      const results = []
      for (const modelData of selectedModels) {
        const result = await prisma.model.upsert({
          where: { 
            subscriptionPlanId_modelId: {
              subscriptionPlanId: planId,
              modelId: modelData.modelId
            }
          },
          update: {
            ...modelData,
            subscriptionPlanId: planId,
            updatedAt: new Date()
          },
          create: {
            ...modelData,
            subscriptionPlanId: planId
          },
          include: {
            subscriptionPlan: true
          }
        })
        
        results.push(result)
      }

      return NextResponse.json({ 
        message: `Successfully added ${results.length} models to ${planId} plan`,
        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 }
    )
  }
}