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

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

// GET /api/prompts/[id]/versions/[versionId] - 获取特定版本
export async function GET(request: NextRequest, { params }: RouteParams) {
  try {
    const { id, versionId } = 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 prompt = await prisma.prompt.findFirst({
      where: { id, userId }
    })

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

    // 获取特定版本
    const version = await prisma.promptVersion.findFirst({
      where: {
        id: versionId,
        promptId: id
      }
    })

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

    return NextResponse.json(version)

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

// POST /api/prompts/[id]/versions/[versionId]/restore - 恢复到特定版本
export async function POST(request: NextRequest, { params }: RouteParams) {
  try {
    const { id, versionId } = await params
    const body = await request.json()
    const { userId } = body

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

    // 验证 prompt 是否存在且属于用户
    const prompt = await prisma.prompt.findFirst({
      where: { id, userId },
      include: {
        versions: {
          orderBy: { version: 'desc' },
          take: 1
        }
      }
    })

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

    // 获取要恢复的版本
    const versionToRestore = await prisma.promptVersion.findFirst({
      where: {
        id: versionId,
        promptId: id
      }
    })

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

    // 创建新版本（基于要恢复的版本）
    const nextVersion = (prompt.versions[0]?.version || 0) + 1
    const newVersion = await prisma.promptVersion.create({
      data: {
        promptId: id,
        version: nextVersion,
        content: versionToRestore.content,
        changelog: `Restored from version ${versionToRestore.version}`
      }
    })

    // 更新 prompt 的内容
    await prisma.prompt.update({
      where: { id },
      data: { content: versionToRestore.content }
    })

    return NextResponse.json({
      message: 'Version restored successfully',
      newVersion,
      restoredFrom: versionToRestore
    })

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