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

// POST /api/prompts/bulk - 批量操作 prompts
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    
    // Get user from Supabase
    const supabase = createClient()
    const { data: { user }, error: authError } = await supabase.auth.getUser()

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

    // Handle bulk create action
    if (body.prompts && Array.isArray(body.prompts)) {
      return handleBulkCreate(body.prompts, user.id)
    }

    // Handle other bulk actions
    const { action, promptIds } = body

    if (!action || !promptIds || !Array.isArray(promptIds)) {
      return NextResponse.json(
        { error: 'Action and promptIds array are required' },
        { status: 400 }
      )
    }

    // 验证所有 prompts 都属于该用户
    const existingPrompts = await prisma.prompt.findMany({
      where: {
        id: { in: promptIds },
        userId: user.id
      }
    })

    if (existingPrompts.length !== promptIds.length) {
      return NextResponse.json(
        { error: 'Some prompts not found or access denied' },
        { status: 404 }
      )
    }

    let result
    switch (action) {
      case 'delete':
        result = await prisma.prompt.deleteMany({
          where: {
            id: { in: promptIds },
            userId: user.id
          }
        })
        break

      case 'duplicate':
        // 批量复制 prompts
        const promptsToDuplicate = await prisma.prompt.findMany({
          where: {
            id: { in: promptIds },
            userId: user.id
          },
          include: {
            tags: true,
            versions: {
              orderBy: { version: 'desc' },
              take: 1
            }
          }
        })

        const duplicatedPrompts = []
        for (const prompt of promptsToDuplicate) {
          const duplicated = await prisma.prompt.create({
            data: {
              name: `${prompt.name} (Copy)`,
              description: prompt.description,
              content: prompt.content,
              userId: user.id,
              tags: {
                connect: prompt.tags.map(tag => ({ id: tag.id }))
              }
            },
            include: {
              tags: true
            }
          })

          // 创建初始版本
          await prisma.promptVersion.create({
            data: {
              promptId: duplicated.id,
              version: 1,
              content: prompt.content,
              changelog: 'Duplicated from original prompt'
            }
          })

          duplicatedPrompts.push(duplicated)
        }

        result = { duplicated: duplicatedPrompts }
        break

      case 'addTag':
        const { tagName } = body
        if (!tagName) {
          return NextResponse.json(
            { error: 'Tag name is required for addTag action' },
            { status: 400 }
          )
        }

        // 创建或获取标签
        const tag = await prisma.promptTag.upsert({
          where: { name: tagName },
          update: {},
          create: { name: tagName }
        })

        // 为所有选中的 prompts 添加标签
        const updatePromises = promptIds.map(promptId =>
          prisma.prompt.update({
            where: { id: promptId },
            data: {
              tags: {
                connect: { id: tag.id }
              }
            }
          })
        )

        await Promise.all(updatePromises)
        result = { count: promptIds.length }
        break

      case 'removeTag':
        const { tagNameToRemove } = body
        if (!tagNameToRemove) {
          return NextResponse.json(
            { error: 'Tag name is required for removeTag action' },
            { status: 400 }
          )
        }

        const tagToRemove = await prisma.promptTag.findUnique({
          where: { name: tagNameToRemove }
        })

        if (tagToRemove) {
          const updatePromises = promptIds.map(promptId =>
            prisma.prompt.update({
              where: { id: promptId },
              data: {
                tags: {
                  disconnect: { id: tagToRemove.id }
                }
              }
            })
          )

          await Promise.all(updatePromises)
          result = { count: promptIds.length }
        }
        break

      default:
        return NextResponse.json(
          { error: 'Invalid action' },
          { status: 400 }
        )
    }

    return NextResponse.json({
      message: `Bulk ${action} completed successfully`,
      result
    })

  } catch (error) {
    console.error('Error in bulk operation:', error)
    return NextResponse.json(
      { error: 'Failed to perform bulk operation' },
      { status: 500 }
    )
  }
}

interface BulkPromptData {
  name: string
  description?: string
  content: string
  tags?: string[]
}

async function handleBulkCreate(prompts: BulkPromptData[], userId: string) {
  try {
    // Validate each prompt
    for (const prompt of prompts) {
      if (!prompt.name || !prompt.content) {
        return NextResponse.json({ 
          error: 'Each prompt must have name and content' 
        }, { status: 400 })
      }
    }

    // Create prompts in transaction
    const createdPrompts = await prisma.$transaction(async (tx) => {
      const results = []

      for (const promptData of prompts) {
        // Create the prompt
        const prompt = await tx.prompt.create({
          data: {
            name: promptData.name.trim(),
            description: promptData.description?.trim() || null,
            content: promptData.content.trim(),
            userId: userId,
          },
        })

        // Create the initial version
        await tx.promptVersion.create({
          data: {
            promptId: prompt.id,
            version: 1,
            content: promptData.content.trim(),
            changelog: 'Initial version',
          },
        })

        // Handle tags if provided
        if (promptData.tags && Array.isArray(promptData.tags) && promptData.tags.length > 0) {
          const tagObjects = []
          for (const tagName of promptData.tags) {
            if (tagName.trim()) {
              // Find or create tag
              const tag = await tx.promptTag.upsert({
                where: { name: tagName.trim() },
                update: {},
                create: { name: tagName.trim() }
              })
              tagObjects.push(tag)
            }
          }

          // Connect tags to prompt
          if (tagObjects.length > 0) {
            await tx.prompt.update({
              where: { id: prompt.id },
              data: {
                tags: {
                  connect: tagObjects.map(tag => ({ id: tag.id }))
                }
              }
            })
          }
        }

        results.push(prompt)
      }

      return results
    })

    return NextResponse.json({ 
      success: true, 
      count: createdPrompts.length,
      prompts: createdPrompts 
    })

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