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

export async function POST(request: Request) {
  try {
    const { userId, trackId } = await request.json()

    if (!userId || !trackId) {
      return NextResponse.json({ error: "Missing userId or trackId" }, { status: 400 })
    }

    // Insert into listening_history
    await sql`
      INSERT INTO listening_history (user_id, track_id, played_at)
      VALUES (${userId}, ${trackId}, NOW())
    `

    // Increment the track's total_streams
    await sql`
      UPDATE tracks 
      SET total_streams = COALESCE(total_streams, 0) + 1
      WHERE id = ${trackId}
    `

    await sql`
      UPDATE artists 
      SET 
        total_streams = COALESCE(total_streams, 0) + 1,
        monthly_listeners = (
          SELECT COUNT(DISTINCT lh.user_id) 
          FROM listening_history lh
          JOIN tracks t ON lh.track_id = t.id
          WHERE t.artist_id = artists.id
          AND lh.played_at > NOW() - INTERVAL '30 days'
        )
      WHERE id = (SELECT artist_id FROM tracks WHERE id = ${trackId})
    `

    const today = new Date().toISOString().split("T")[0]
    await sql`
      INSERT INTO stream_counts (track_id, date, stream_count, unique_listeners)
      VALUES (${trackId}, ${today}, 1, 1)
      ON CONFLICT (track_id, date) 
      DO UPDATE SET 
        stream_count = stream_counts.stream_count + 1,
        unique_listeners = (
          SELECT COUNT(DISTINCT user_id) 
          FROM listening_history 
          WHERE track_id = ${trackId} 
          AND DATE(played_at) = ${today}
        )
    `

    const currentMonth = new Date()
    const periodStart = new Date(currentMonth.getFullYear(), currentMonth.getMonth(), 1)
    const periodEnd = new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 0)

    await sql`
      INSERT INTO artist_earnings (artist_id, track_id, period_start, period_end, streams, earnings_amount, status)
      SELECT 
        t.artist_id,
        ${trackId},
        ${periodStart.toISOString()}::date,
        ${periodEnd.toISOString()}::date,
        1,
        1,
        'pending'
      FROM tracks t WHERE t.id = ${trackId}
      ON CONFLICT (artist_id, track_id, period_start) 
      DO UPDATE SET 
        streams = artist_earnings.streams + 1,
        earnings_amount = artist_earnings.earnings_amount + 1
    `

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Add to history error:", error)
    return NextResponse.json({ error: "Failed to add to history" }, { status: 500 })
  }
}

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get("userId")
    const limit = Number.parseInt(searchParams.get("limit") || "50")

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

    const history = await sql`
      SELECT 
        lh.id,
        lh.played_at,
        t.id as track_id,
        t.title,
        t.duration_ms,
        t.cover_url,
        t.audio_url,
        a.id as artist_id,
        a.name as artist_name
      FROM listening_history lh
      JOIN tracks t ON lh.track_id = t.id
      LEFT JOIN artists a ON t.artist_id = a.id
      WHERE lh.user_id = ${userId}
      ORDER BY lh.played_at DESC
      LIMIT ${limit}
    `

    return NextResponse.json({ data: history })
  } catch (error) {
    console.error("Get history error:", error)
    return NextResponse.json({ error: "Failed to get history" }, { status: 500 })
  }
}
