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

export async function GET() {
  try {
    let payouts: any[] = []
    let rates: any[] = []

    try {
      payouts = await sql`
        SELECT 
          ae.*,
          a.name as artist_name,
          a.avatar_url as artist_avatar,
          t.title as track_title
        FROM artist_earnings ae
        LEFT JOIN artists a ON ae.artist_id = a.id
        LEFT JOIN tracks t ON ae.track_id = t.id
        ORDER BY ae.created_at DESC
        LIMIT 50
      `
    } catch (e) {
      console.log("Artist earnings fetch error:", e)
    }

    try {
      rates = await sql`
        SELECT 
          id,
          name,
          subscription_type,
          rate_per_stream,
          is_active
        FROM royalty_rates 
        WHERE is_active = true
        ORDER BY rate_per_stream DESC
      `
    } catch (e) {
      console.log("Royalty rates fetch error:", e)
      // Default rates if table is empty
      rates = [
        { name: "Premium", subscription_type: "premium", rate_per_stream: 0.00262 },
        { name: "Free (Ads)", subscription_type: "free", rate_per_stream: 0.00066 },
        { name: "Family", subscription_type: "family", rate_per_stream: 0.0023 },
        { name: "Student", subscription_type: "student", rate_per_stream: 0.00131 },
      ]
    }

    const totalPaid = payouts
      .filter((p: any) => p.status === "paid")
      .reduce((acc: number, p: any) => acc + (p.earnings_amount || 0), 0)
    const totalPending = payouts
      .filter((p: any) => p.status === "pending")
      .reduce((acc: number, p: any) => acc + (p.earnings_amount || 0), 0)

    return NextResponse.json({
      payouts: payouts.map((p: any) => ({
        id: p.id,
        artist_id: p.artist_id,
        artist_name: p.artist_name,
        artist_avatar: p.artist_avatar,
        track_title: p.track_title,
        amount: p.earnings_amount,
        streams: p.streams,
        period_start: p.period_start,
        period_end: p.period_end,
        status: p.status,
        created_at: p.created_at,
      })),
      stats: {
        totalPaid,
        totalPending,
        artistCount: new Set(payouts.map((p: any) => p.artist_id)).size,
        avgRate:
          rates.length > 0
            ? rates.reduce((acc: number, r: any) => acc + Number(r.rate_per_stream || 0), 0) / rates.length
            : 0.002,
      },
      rates: rates.map((r: any) => ({
        id: r.id,
        tier: r.name,
        subscriptionType: r.subscription_type,
        rate: Number(r.rate_per_stream) * 1000, // Convert to rate per 1000 streams
        percentage: 25, // Default percentage
      })),
    })
  } catch (error) {
    console.error("Error fetching royalties:", error)
    return NextResponse.json({
      payouts: [],
      stats: { totalPaid: 0, totalPending: 0, artistCount: 0, avgRate: 0 },
      rates: [],
    })
  }
}
