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

// GET /api/simulator/prompts - 获取用户的提示词列表，包含所有版本信息用于模拟器
export async function GET(request: NextRequest) {
  try {
    const session = await auth.api.getSession({
      headers: await headers()
    })

    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const user = session.user

    const { searchParams } = new URL(request.url)
    const limit = parseInt(searchParams.get('limit') || '100')

    // 获取用户的提示词，包含所有版本
    const prompts = await prisma.prompt.findMany({
      where: {
        userId: user.id,
      },
      include: {
        versions: {
          orderBy: { version: 'desc' },
          select: {
            id: true,
            version: true,
            content: true,
          }
        }
      },
      orderBy: { updatedAt: 'desc' },
      take: limit,
    })

    // 转换数据结构，确保包含所有版本信息
    const promptsWithVersions = prompts.map(prompt => ({
      id: prompt.id,
      name: prompt.name,
      content: prompt.content,
      versions: prompt.versions
    }))

    return NextResponse.json({
      prompts: promptsWithVersions
    })

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