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

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url)
    const userId = searchParams.get('userId')

    if (!userId) {
      return NextResponse.json({ error: 'Missing userId' }, { status: 400 })
    }

    // Fetch all prompts with their versions, tags, and albums
    const prompts = await prisma.prompt.findMany({
      where: { userId },
      include: {
        tags: {
          select: {
            name: true,
            color: true
          }
        },
        versions: {
          select: {
            version: true,
            content: true,
            changelog: true,
            createdAt: true
          },
          orderBy: {
            version: 'asc'
          }
        },
        album: {
          select: {
            name: true,
            description: true
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    })

    // Transform the data for export
    const exportData = {
      exportVersion: '1.0',
      exportDate: new Date().toISOString(),
      userId,
      totalPrompts: prompts.length,
      prompts: prompts.map(prompt => ({
        id: prompt.id,
        name: prompt.name,
        content: prompt.content,
        description: prompt.description,
        permissions: prompt.permissions,
        visibility: prompt.visibility,
        tags: prompt.tags.map(tag => ({
          name: tag.name,
          color: tag.color
        })),
        album: prompt.album ? {
          name: prompt.album.name,
          description: prompt.album.description
        } : null,
        versions: prompt.versions,
        createdAt: prompt.createdAt.toISOString(),
        updatedAt: prompt.updatedAt.toISOString()
      }))
    }

    const fileName = `prompts-export-${new Date().toISOString().split('T')[0]}.json`
    
    return new NextResponse(JSON.stringify(exportData, null, 2), {
      headers: {
        'Content-Type': 'application/json',
        'Content-Disposition': `attachment; filename="${fileName}"`
      }
    })
  } catch (error) {
    console.error('Export error:', error)
    return NextResponse.json({ error: 'Export failed' }, { status: 500 })
  }
}