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

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

// GET /api/prompts/[id]/tests - 获取 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')
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '10')

    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 skip = (page - 1) * limit

    // 获取测试历史
    const [tests, total] = await Promise.all([
      prisma.promptTestRun.findMany({
        where: { promptId: id },
        orderBy: { createdAt: 'desc' },
        skip,
        take: limit
      }),
      prisma.promptTestRun.count({
        where: { promptId: id }
      })
    ])

    // 计算统计信息
    const [totalCount, successCount] = await Promise.all([
      prisma.promptTestRun.count({
        where: { promptId: id }
      }),
      prisma.promptTestRun.count({
        where: { promptId: id, success: true }
      })
    ])

    const successRate = totalCount > 0
      ? ((successCount / totalCount) * 100).toFixed(1)
      : '0'

    return NextResponse.json({
      tests,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit)
      },
      stats: {
        totalRuns: totalCount,
        successfulRuns: successCount,
        successRate: `${successRate}%`
      }
    })

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