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

// GET - Fetch user purchase history
export async function GET(request: NextRequest) {
  try {
    const userId = request.headers.get("x-user-id")

    if (!userId) {
      return NextResponse.json({ error: "Non autorisé" }, { status: 401 })
    }

    // Fetch purchases with details
    const purchases = await sql`
      SELECT 
        p.id,
        p.purchase_type,
        p.item_id,
        p.price_fcfa,
        p.currency,
        p.payment_method,
        p.payment_reference,
        p.status,
        p.created_at,
        CASE 
          WHEN p.purchase_type = 'track' THEN t.title
          WHEN p.purchase_type = 'album' THEN a.title
        END as item_title,
        CASE 
          WHEN p.purchase_type = 'track' THEN t.cover_url
          WHEN p.purchase_type = 'album' THEN a.cover_url
        END as item_cover,
        CASE 
          WHEN p.purchase_type = 'track' THEN art1.name
          WHEN p.purchase_type = 'album' THEN art2.name
        END as artist_name
      FROM purchases p
      LEFT JOIN tracks t ON p.purchase_type = 'track' AND p.item_id = t.id
      LEFT JOIN albums a ON p.purchase_type = 'album' AND p.item_id = a.id
      LEFT JOIN artists art1 ON t.artist_id = art1.id
      LEFT JOIN artists art2 ON a.artist_id = art2.id
      WHERE p.user_id = ${userId}
      ORDER BY p.created_at DESC
      LIMIT 100
    `

    // Calculate total spent
    const stats = await sql`
      SELECT 
        COUNT(*) as total_purchases,
        SUM(price_fcfa) as total_spent,
        COUNT(CASE WHEN purchase_type = 'track' THEN 1 END) as tracks_purchased,
        COUNT(CASE WHEN purchase_type = 'album' THEN 1 END) as albums_purchased
      FROM purchases
      WHERE user_id = ${userId} AND status = 'completed'
    `

    return NextResponse.json({
      purchases,
      stats: stats[0] || { total_purchases: 0, total_spent: 0, tracks_purchased: 0, albums_purchased: 0 },
    })
  } catch (error: any) {
    console.error("Error fetching purchases:", error)
    return NextResponse.json({ error: "Erreur serveur" }, { status: 500 })
  }
}

// POST - Create a new purchase
export async function POST(request: NextRequest) {
  try {
    const userId = request.headers.get("x-user-id")
    if (!userId) {
      return NextResponse.json({ error: "Non autorisé" }, { status: 401 })
    }

    const body = await request.json()
    const { purchaseType, itemId, paymentMethod } = body

    if (!purchaseType || !itemId) {
      return NextResponse.json({ error: "Type et ID requis" }, { status: 400 })
    }

    // Check if already owned
    const existing = await sql`
      SELECT id FROM user_owned_content
      WHERE user_id = ${userId}
      AND content_type = ${purchaseType}
      AND content_id = ${itemId}
    `

    if (existing.length > 0) {
      return NextResponse.json({ error: "Déjà acheté" }, { status: 400 })
    }

    // Get item price
    let price = 0
    if (purchaseType === "track") {
      const track = await sql`SELECT price_fcfa FROM tracks WHERE id = ${itemId}`
      price = track[0]?.price_fcfa || 500
    } else if (purchaseType === "album") {
      const album = await sql`SELECT price_fcfa FROM albums WHERE id = ${itemId}`
      price = album[0]?.price_fcfa || 3000
    }

    // Create purchase
    const purchase = await sql`
      INSERT INTO purchases (user_id, purchase_type, item_id, price_fcfa, payment_method, status)
      VALUES (${userId}, ${purchaseType}, ${itemId}, ${price}, ${paymentMethod || "card"}, 'completed')
      RETURNING *
    `

    // Add to owned content
    await sql`
      INSERT INTO user_owned_content (user_id, content_type, content_id, purchase_id)
      VALUES (${userId}, ${purchaseType}, ${itemId}, ${purchase[0].id})
    `

    // Create payment transaction
    await sql`
      INSERT INTO payment_transactions (user_id, purchase_id, amount, status, payment_method, description)
      VALUES (
        ${userId},
        ${purchase[0].id},
        ${price},
        'completed',
        ${paymentMethod || "card"},
        ${`Achat ${purchaseType}: ${itemId}`}
      )
    `

    return NextResponse.json({ purchase: purchase[0], message: "Achat réussi" })
  } catch (error: any) {
    console.error("Error creating purchase:", error)
    return NextResponse.json({ error: "Erreur lors de l'achat" }, { status: 500 })
  }
}
