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

interface RouteParams {
  params: Promise<{ id: string }>
}

// GET /api/prompts/[id] - 获取单个 prompt
export async function GET(request: NextRequest, { params }: RouteParams) {
  try {
    const { id } = await params
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')

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

    const prompt = await prisma.prompt.findFirst({
      where: {
        id,
        userId
      },
      include: {
        tags: true,
        versions: {
          orderBy: { version: 'desc' }
        },
        tests: {
          orderBy: { createdAt: 'desc' },
          take: 10
        }
      }
    })

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

    const promptWithMetadata = {
      ...prompt,
      lastUsed: prompt.tests[0]?.createdAt || null,
      currentVersion: prompt.versions[0]?.version || 1,
      tags: prompt.tags.map(tag => tag.name),
      usage: prompt.tests.length
    }

    return NextResponse.json(promptWithMetadata)

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

// PUT /api/prompts/[id] - 更新 prompt
export async function PUT(request: NextRequest, { params }: RouteParams) {
  try {
    const { id } = await params
    const body = await request.json()
    const { name, description, content, tags, userId, permissions } = body

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

    // 验证 prompt 是否存在且属于用户，并获取用户信息
    const existingPrompt = await prisma.prompt.findFirst({
      where: { id, userId },
      include: { 
        versions: { orderBy: { version: 'desc' } },
        user: true
      }
    })

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

    // 处理标签
    const tagObjects = []
    if (tags && tags.length > 0) {
      for (const tagName of tags) {
        const tag = await prisma.promptTag.upsert({
          where: { name: tagName },
          update: {},
          create: { name: tagName }
        })
        tagObjects.push(tag)
      }
    }

    // 检查内容是否有变化，如果有则创建新版本
    const currentVersion = existingPrompt.versions[0]
    let shouldCreateVersion = false

    if (content && currentVersion && content !== currentVersion.content) {
      shouldCreateVersion = true
    } else if (content && !currentVersion) {
      // 如果没有版本历史，创建第一个版本
      shouldCreateVersion = true
    }

    // 准备更新数据
    const updateData: {
      name?: string
      description?: string | null
      content?: string
      permissions?: 'private' | 'public'
      visibility?: 'under_review' | 'published' | null
      tags?: {
        set: never[]
        connect: { id: string }[]
      }
    } = {}
    
    if (name !== undefined) updateData.name = name
    if (description !== undefined) updateData.description = description
    if (content !== undefined) updateData.content = content
    if (permissions !== undefined) {
      updateData.permissions = permissions
      // 如果设置为公开，自动设置审核状态
      if (permissions === 'public') {
        updateData.visibility = 'under_review'
      } else if (permissions === 'private') {
        updateData.visibility = null
      }
    }
    
    // 处理标签更新
    if (tags !== undefined) {
      updateData.tags = {
        set: [], // 先清空所有标签
        connect: tagObjects.map(tag => ({ id: tag.id })) // 然后连接新标签
      }
    }

    // 更新 prompt
    const updatedPrompt = await prisma.prompt.update({
      where: { id },
      data: updateData,
      include: {
        tags: true,
        versions: {
          orderBy: { version: 'desc' }
        }
      }
    })

    // 如果内容有变化，创建新版本并处理版本限制
    if (shouldCreateVersion && content) {
      const user = existingPrompt.user
      const currentVersionCount = existingPrompt.versions.length
      
      // 检查是否需要删除旧版本以遵守版本限制
      const versionsToDelete = getVersionsToDelete(currentVersionCount, user)
      
      if (versionsToDelete > 0) {
        // 删除最旧的版本
        const oldestVersions = existingPrompt.versions
          .slice(-versionsToDelete)
          .map(v => v.id)
        
        await prisma.promptVersion.deleteMany({
          where: {
            id: { in: oldestVersions }
          }
        })
      }
      
      const nextVersion = (currentVersion?.version || 0) + 1
      await prisma.promptVersion.create({
        data: {
          promptId: id,
          version: nextVersion,
          content,
          changelog: `Updated to version ${nextVersion}`
        }
      })
    }

    // 处理返回数据格式，确保tags是字符串数组
    const promptWithMetadata = {
      ...updatedPrompt,
      tags: updatedPrompt.tags.map(tag => tag.name)
    }

    return NextResponse.json(promptWithMetadata)

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

// DELETE /api/prompts/[id] - 删除 prompt
export async function DELETE(request: NextRequest, { params }: RouteParams) {
  try {
    const { id } = await params
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')

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

    // 验证 prompt 是否存在且属于用户
    const existingPrompt = await prisma.prompt.findFirst({
      where: { id, userId }
    })

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

    // 删除 prompt（级联删除相关数据）
    await prisma.prompt.delete({
      where: { id }
    })

    return NextResponse.json({ message: 'Prompt deleted successfully' })

  } catch (error) {
    console.error('Error deleting prompt:', error)
    return NextResponse.json(
      { error: 'Failed to delete prompt' },
      { status: 500 }
    )
  }
}
