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

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

// GET /api/prompts/[id]/versions - 获取 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 })
    }

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

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

    // 获取所有版本
    const versions = await prisma.promptVersion.findMany({
      where: { promptId: id },
      orderBy: { version: 'desc' }
    })

    return NextResponse.json(versions)

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

// POST /api/prompts/[id]/versions - 创建新版本
export async function POST(request: NextRequest, { params }: RouteParams) {
  try {
    const { id } = await params
    const body = await request.json()
    const { content, changelog, userId } = body

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

    if (!content) {
      return NextResponse.json(
        { error: 'Content is required' },
        { status: 400 }
      )
    }

    // 验证 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 nextVersion = (prompt.versions[0]?.version || 0) + 1

    // 创建新版本
    const newVersion = await prisma.promptVersion.create({
      data: {
        promptId: id,
        version: nextVersion,
        content,
        changelog: changelog || `Version ${nextVersion}`
      }
    })

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

    return NextResponse.json(newVersion, { status: 201 })

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