import { type NextRequest, NextResponse } from "next/server"
import { sql } from "@/lib/db"

export async function POST(request: NextRequest) {
  try {
    const { type, startDate, endDate } = await request.json()

    let data: any[] = []
    let title = ""

    switch (type) {
      case "streams":
        title = "Rapport des Streams"
        data = await sql`
          SELECT 
            t.title,
            a.name as artist,
            COUNT(lh.id) as streams,
            DATE_TRUNC('day', lh.played_at) as date
          FROM listening_history lh
          JOIN tracks t ON lh.track_id = t.id
          JOIN artists a ON t.artist_id = a.id
          WHERE lh.played_at BETWEEN ${startDate}::date AND ${endDate}::date
          GROUP BY t.id, t.title, a.name, DATE_TRUNC('day', lh.played_at)
          ORDER BY streams DESC
          LIMIT 100
        `
        break

      case "revenue":
        title = "Rapport des Revenus"
        data = await sql`
          SELECT 
            DATE_TRUNC('day', created_at) as date,
            type,
            SUM(amount) as total_amount,
            COUNT(*) as transaction_count
          FROM payment_transactions
          WHERE status = 'completed'
          AND created_at BETWEEN ${startDate}::date AND ${endDate}::date
          GROUP BY DATE_TRUNC('day', created_at), type
          ORDER BY date DESC
        `
        break

      case "users":
        title = "Rapport des Utilisateurs"
        data = await sql`
          SELECT 
            DATE_TRUNC('day', created_at) as date,
            role,
            COUNT(*) as new_users
          FROM users
          WHERE created_at BETWEEN ${startDate}::date AND ${endDate}::date
          GROUP BY DATE_TRUNC('day', created_at), role
          ORDER BY date DESC
        `
        break

      case "artists":
        title = "Rapport des Artistes"
        data = await sql`
          SELECT 
            a.name,
            COUNT(DISTINCT t.id) as track_count,
            SUM(t.total_streams) as total_streams,
            a.verified
          FROM artists a
          LEFT JOIN tracks t ON a.id = t.artist_id
          WHERE a.created_at BETWEEN ${startDate}::date AND ${endDate}::date
          GROUP BY a.id, a.name, a.verified
          ORDER BY total_streams DESC
          LIMIT 50
        `
        break

      default:
        return NextResponse.json({ error: "Invalid export type" }, { status: 400 })
    }

    // For a real PDF, you would use a library like jsPDF or pdfkit
    const headers = Object.keys(data[0] || {})
    const csvRows = [headers.join(",")]

    data.forEach((row) => {
      const values = headers.map((header) => {
        const value = row[header]
        return typeof value === "string" ? `"${value}"` : value
      })
      csvRows.push(values.join(","))
    })

    const csv = csvRows.join("\n")

    return new NextResponse(csv, {
      status: 200,
      headers: {
        "Content-Type": "text/csv",
        "Content-Disposition": `attachment; filename="${title.replace(/\s+/g, "_")}_${startDate}_${endDate}.csv"`,
      },
    })
  } catch (error) {
    console.error("Error generating export:", error)
    return NextResponse.json({ error: "Failed to generate export" }, { status: 500 })
  }
}
