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

// GET /api/tags - 获取所有标签
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')

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

    // 获取用户使用过的所有标签
    const tags = await prisma.promptTag.findMany({
      include: {
        prompts: {
          where: {
            userId
          },
          select: {
            id: true
          }
        }
      }
    })

    // 只返回用户使用过的标签，并包含使用次数
    const userTags = tags
      .filter(tag => tag.prompts.length > 0)
      .map(tag => ({
        id: tag.id,
        name: tag.name,
        color: tag.color,
        count: tag.prompts.length
      }))
      .sort((a, b) => b.count - a.count) // 按使用次数排序

    return NextResponse.json(userTags)

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

// POST /api/tags - 创建新标签
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { name, color } = body

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

    const tag = await prisma.promptTag.upsert({
      where: { name },
      update: { color: color || '#3B82F6' },
      create: { 
        name, 
        color: color || '#3B82F6' 
      }
    })

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

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