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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const artistId = searchParams.get("artistId")
    const year = searchParams.get("year") || new Date().getFullYear().toString()

    if (!artistId) {
      return NextResponse.json({ error: "Artist ID required" }, { status: 400 })
    }

    // Get earnings history
    const earningsHistory = await sql`
      SELECT 
        TO_CHAR(period_start, 'Mon YYYY') as month,
        SUM(streams) as streams,
        SUM(earnings_amount) as earnings,
        status
      FROM artist_earnings
      WHERE artist_id = ${artistId}
        AND EXTRACT(YEAR FROM period_start) = ${Number.parseInt(year)}
      GROUP BY TO_CHAR(period_start, 'Mon YYYY'), period_start, status
      ORDER BY period_start DESC
      LIMIT 12
    `

    // Get totals
    const totals = await sql`
      SELECT 
        SUM(CASE WHEN status = 'pending' THEN earnings_amount ELSE 0 END) as pending_amount,
        SUM(CASE WHEN status = 'paid' THEN earnings_amount ELSE 0 END) as paid_amount,
        SUM(earnings_amount) as total_earnings,
        SUM(streams) as total_streams
      FROM artist_earnings
      WHERE artist_id = ${artistId}
        AND EXTRACT(YEAR FROM period_start) = ${Number.parseInt(year)}
    `

    // Get current month earnings
    const currentMonth = await sql`
      SELECT 
        SUM(earnings_amount) as earnings,
        SUM(streams) as streams
      FROM artist_earnings
      WHERE artist_id = ${artistId}
        AND EXTRACT(MONTH FROM period_start) = EXTRACT(MONTH FROM CURRENT_DATE)
        AND EXTRACT(YEAR FROM period_start) = EXTRACT(YEAR FROM CURRENT_DATE)
    `

    // Get last month for comparison
    const lastMonth = await sql`
      SELECT SUM(earnings_amount) as earnings
      FROM artist_earnings
      WHERE artist_id = ${artistId}
        AND period_start >= DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month')
        AND period_start < DATE_TRUNC('month', CURRENT_DATE)
    `

    // Get revenue breakdown by source (simulate with track data for now)
    const breakdown = await sql`
      SELECT 
        COALESCE(t.title, 'Autres') as source,
        SUM(ae.earnings_amount) as amount
      FROM artist_earnings ae
      LEFT JOIN tracks t ON ae.track_id = t.id
      WHERE ae.artist_id = ${artistId}
        AND EXTRACT(YEAR FROM ae.period_start) = ${Number.parseInt(year)}
      GROUP BY t.title
      ORDER BY amount DESC
      LIMIT 5
    `

    // Calculate percentage change
    const currentMonthEarnings = Number(currentMonth[0]?.earnings || 0)
    const lastMonthEarnings = Number(lastMonth[0]?.earnings || 0)
    const percentChange =
      lastMonthEarnings > 0 ? (((currentMonthEarnings - lastMonthEarnings) / lastMonthEarnings) * 100).toFixed(1) : 0

    // Get available balance (pending earnings)
    const availableBalance = Number(totals[0]?.pending_amount || 0)

    return NextResponse.json({
      earningsHistory: earningsHistory.map((row) => ({
        month: row.month,
        streams: Number(row.streams || 0),
        earnings: Number(row.earnings || 0),
        status: row.status,
      })),
      availableBalance,
      currentMonthEarnings,
      pendingAmount: Number(totals[0]?.pending_amount || 0),
      totalYearEarnings: Number(totals[0]?.total_earnings || 0),
      percentChange: Number(percentChange),
      breakdown: breakdown.map((row) => ({
        source: row.source,
        amount: Number(row.amount || 0),
      })),
    })
  } catch (error) {
    console.error("Error fetching artist earnings:", error)
    return NextResponse.json({ error: "Failed to fetch earnings" }, { status: 500 })
  }
}

// Request payout
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { artistId, amount, paymentMethod } = body

    if (!artistId || !amount) {
      return NextResponse.json({ error: "Artist ID and amount required" }, { status: 400 })
    }

    // Create payout request
    const result = await sql`
      INSERT INTO artist_payouts (artist_id, amount, payment_method, status)
      VALUES (${artistId}, ${amount}, ${paymentMethod || "mobile_money"}, 'pending')
      RETURNING *
    `

    return NextResponse.json(result[0])
  } catch (error) {
    console.error("Error requesting payout:", error)
    return NextResponse.json({ error: "Failed to request payout" }, { status: 500 })
  }
}
