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

const prisma = new PrismaClient()

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const search = searchParams.get('search') || ''
    const tag = searchParams.get('tag') || ''
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '12')
    const sortBy = searchParams.get('sortBy') || 'createdAt'
    const sortOrder = searchParams.get('sortOrder') || 'desc'

    const skip = (page - 1) * limit

    // 构建where条件
    const where: Record<string, unknown> = {
      permissions: 'public',
      visibility: 'published',
    }

    // 搜索条件：根据名称和描述匹配
    if (search) {
      where.OR = [
        { name: { contains: search, mode: 'insensitive' } },
        { description: { contains: search, mode: 'insensitive' } },
      ]
    }

    // 标签过滤
    if (tag) {
      where.tags = {
        some: {
          name: tag
        }
      }
    }

    // 排序条件
    const orderBy: Record<string, string> = {}
    if (sortBy === 'name') {
      orderBy.name = sortOrder
    } else {
      orderBy.createdAt = sortOrder
    }

    // 获取总数和数据
    const [total, prompts] = await Promise.all([
      prisma.prompt.count({ where }),
      prisma.prompt.findMany({
        where,
        skip,
        take: limit,
        orderBy,
        include: {
          user: {
            select: {
              id: true,
              username: true,
              avatar: true,
            }
          },
          tags: {
            select: {
              id: true,
              name: true,
              color: true,
            }
          },
          versions: {
            orderBy: {
              version: 'desc'
            },
            take: 1,
            select: {
              content: true,
              version: true,
              createdAt: true,
            }
          },
          _count: {
            select: {
              versions: true,
            }
          }
        }
      })
    ])

    const totalPages = Math.ceil(total / limit)

    return NextResponse.json({
      prompts,
      pagination: {
        page,
        limit,
        total,
        totalPages,
        hasNext: page < totalPages,
        hasPrev: page > 1,
      }
    })
  } catch (error) {
    console.error('Error fetching plaza prompts:', error)
    return NextResponse.json(
      { error: 'Failed to fetch prompts' },
      { status: 500 }
    )
  }
}