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

export async function GET(request: NextRequest) {
  try {
    const adminId = await getAdminUser(request)
    if (!adminId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }

    const { searchParams } = new URL(request.url)
    const page = Number.parseInt(searchParams.get("page") || "1")
    const limit = Number.parseInt(searchParams.get("limit") || "50")
    const search = searchParams.get("search") || ""
    const offset = (page - 1) * limit

    let tracks
    let total

    if (search) {
      tracks = await sql`
        SELECT t.*, 
          u.name as artist_name,
          a.title as album_title
        FROM tracks t
        LEFT JOIN users u ON t.artist_id = u.id
        LEFT JOIN albums a ON t.album_id = a.id
        WHERE t.title ILIKE ${"%" + search + "%"}
           OR u.name ILIKE ${"%" + search + "%"}
        ORDER BY t.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
      const countResult = await sql`
        SELECT COUNT(*) as count FROM tracks t
        LEFT JOIN users u ON t.artist_id = u.id
        WHERE t.title ILIKE ${"%" + search + "%"}
           OR u.name ILIKE ${"%" + search + "%"}
      `
      total = Number.parseInt(countResult[0].count)
    } else {
      tracks = await sql`
        SELECT t.*, 
          u.name as artist_name,
          a.title as album_title
        FROM tracks t
        LEFT JOIN users u ON t.artist_id = u.id
        LEFT JOIN albums a ON t.album_id = a.id
        ORDER BY t.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
      const countResult = await sql`SELECT COUNT(*) as count FROM tracks`
      total = Number.parseInt(countResult[0].count)
    }

    return NextResponse.json({
      tracks,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit),
      },
    })
  } catch (error) {
    console.error("Error fetching tracks:", error)
    return NextResponse.json({ tracks: [], pagination: { page: 1, limit: 50, total: 0, pages: 0 } })
  }
}

export async function POST(request: NextRequest) {
  try {
    const adminId = await getAdminUser(request)
    if (!adminId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }

    const body = await request.json()
    const {
      title,
      artist_id,
      album_id,
      genre_id,
      duration,
      audio_url,
      cover_url,
      lyrics,
      is_explicit,
      is_featured,
      track_number,
      status,
    } = body

    const result = await sql`
      INSERT INTO tracks (
        title, artist_id, album_id, genre_id, duration,
        audio_url, cover_url, lyrics, is_explicit, is_featured,
        track_number, status
      ) VALUES (
        ${title}, ${artist_id || null}, ${album_id || null}, ${genre_id || null}, ${duration || 0},
        ${audio_url || null}, ${cover_url || null}, ${lyrics || null}, 
        ${is_explicit || false}, ${is_featured || false},
        ${track_number || null}, ${status || "published"}
      )
      RETURNING *
    `
    return NextResponse.json(result[0])
  } catch (error) {
    console.error("Error creating track:", error)
    return NextResponse.json({ error: "Failed to create track" }, { status: 500 })
  }
}
