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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const random = searchParams.get("random")

    if (random === "true") {
      const limit = Math.min(Number.parseInt(searchParams.get("limit") || "50"), 100) // Cap limit to prevent abuse
      const genre = searchParams.get("genre")

      let tracks
      if (genre) {
        const genrePattern = `%${genre}%`
        tracks = await sql`
          SELECT t.*, 
                 a.name as artist_name, a.avatar_url as artist_avatar,
                 al.title as album_title, al.cover_url as album_cover
          FROM tracks t
          LEFT JOIN artists a ON t.artist_id = a.id
          LEFT JOIN albums al ON t.album_id = al.id
          WHERE t.status = 'published' 
            AND (t.genres ILIKE ${genrePattern} OR t.genres = ${genre})
          ORDER BY RANDOM()
          LIMIT ${limit}
        `
      } else {
        tracks = await sql`
          SELECT t.*, 
                 a.name as artist_name, a.avatar_url as artist_avatar,
                 al.title as album_title, al.cover_url as album_cover
          FROM tracks t
          LEFT JOIN artists a ON t.artist_id = a.id
          LEFT JOIN albums al ON t.album_id = al.id
          WHERE t.status = 'published'
          ORDER BY RANDOM()
          LIMIT ${limit}
        `
      }

      return NextResponse.json({
        data: tracks,
        total: tracks.length,
      })
    }

    const { page, limit, offset } = getPaginationValues({
      page: Math.max(1, Number.parseInt(searchParams.get("page") || "1")),
      limit: Math.min(100, Number.parseInt(searchParams.get("limit") || "20")),
    })
    const search = searchParams.get("search")?.trim() || ""
    const status = searchParams.get("status")
    const artistId = searchParams.get("artist_id") || searchParams.get("artistId")

    const validStatuses = ["draft", "pending", "published", "archived", "rejected"]
    if (status && !validStatuses.includes(status)) {
      return NextResponse.json({ error: "Invalid status" }, { status: 400 })
    }

    let tracks
    let countResult

    if (search && status && artistId) {
      const searchPattern = `%${search}%`
      tracks = await sql`
        SELECT t.*, 
               a.name as artist_name, a.avatar_url as artist_avatar,
               al.title as album_title, al.cover_url as album_cover
        FROM tracks t
        LEFT JOIN artists a ON t.artist_id = a.id
        LEFT JOIN albums al ON t.album_id = al.id
        WHERE t.status = ${status} AND t.title ILIKE ${searchPattern} AND t.artist_id = ${artistId}
        ORDER BY t.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
      countResult = await sql`
        SELECT COUNT(*) as total FROM tracks t
        WHERE t.status = ${status} AND t.title ILIKE ${searchPattern} AND t.artist_id = ${artistId}
      `
    } else if (search && status) {
      const searchPattern = `%${search}%`
      tracks = await sql`
        SELECT t.*, 
               a.name as artist_name, a.avatar_url as artist_avatar,
               al.title as album_title, al.cover_url as album_cover
        FROM tracks t
        LEFT JOIN artists a ON t.artist_id = a.id
        LEFT JOIN albums al ON t.album_id = al.id
        WHERE t.status = ${status} AND t.title ILIKE ${searchPattern}
        ORDER BY t.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
      countResult = await sql`
        SELECT COUNT(*) as total FROM tracks t
        WHERE t.status = ${status} AND t.title ILIKE ${searchPattern}
      `
    } else if (search && artistId) {
      const searchPattern = `%${search}%`
      tracks = await sql`
        SELECT t.*, 
               a.name as artist_name, a.avatar_url as artist_avatar,
               al.title as album_title, al.cover_url as album_cover
        FROM tracks t
        LEFT JOIN artists a ON t.artist_id = a.id
        LEFT JOIN albums al ON t.album_id = al.id
        WHERE t.title ILIKE ${searchPattern} AND t.artist_id = ${artistId}
        ORDER BY t.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
      countResult = await sql`
        SELECT COUNT(*) as total FROM tracks t
        WHERE t.title ILIKE ${searchPattern} AND t.artist_id = ${artistId}
      `
    } else if (status && artistId) {
      tracks = await sql`
        SELECT t.*, 
               a.name as artist_name, a.avatar_url as artist_avatar,
               al.title as album_title, al.cover_url as album_cover
        FROM tracks t
        LEFT JOIN artists a ON t.artist_id = a.id
        LEFT JOIN albums al ON t.album_id = al.id
        WHERE t.status = ${status} AND t.artist_id = ${artistId}
        ORDER BY t.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
      countResult = await sql`
        SELECT COUNT(*) as total FROM tracks t
        WHERE t.status = ${status} AND t.artist_id = ${artistId}
      `
    } else if (search) {
      const searchPattern = `%${search}%`
      tracks = await sql`
        SELECT t.*, 
               a.name as artist_name, a.avatar_url as artist_avatar,
               al.title as album_title, al.cover_url as album_cover
        FROM tracks t
        LEFT JOIN artists a ON t.artist_id = a.id
        LEFT JOIN albums al ON t.album_id = al.id
        WHERE t.title ILIKE ${searchPattern}
        ORDER BY t.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
      countResult = await sql`
        SELECT COUNT(*) as total FROM tracks t
        WHERE t.title ILIKE ${searchPattern}
      `
    } else if (status) {
      tracks = await sql`
        SELECT t.*, 
               a.name as artist_name, a.avatar_url as artist_avatar,
               al.title as album_title, al.cover_url as album_cover
        FROM tracks t
        LEFT JOIN artists a ON t.artist_id = a.id
        LEFT JOIN albums al ON t.album_id = al.id
        WHERE t.status = ${status}
        ORDER BY t.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
      countResult = await sql`
        SELECT COUNT(*) as total FROM tracks t
        WHERE t.status = ${status}
      `
    } else if (artistId) {
      // When filtering by artist_id, show ALL their tracks (not just published)
      tracks = await sql`
        SELECT t.*, 
               a.name as artist_name, a.avatar_url as artist_avatar,
               al.title as album_title, al.cover_url as album_cover
        FROM tracks t
        LEFT JOIN artists a ON t.artist_id = a.id
        LEFT JOIN albums al ON t.album_id = al.id
        WHERE t.artist_id = ${artistId}
        ORDER BY t.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
      countResult = await sql`
        SELECT COUNT(*) as total FROM tracks t
        WHERE t.artist_id = ${artistId}
      `
    } else {
      // Default: show all tracks for admin view (no status filter)
      tracks = await sql`
        SELECT t.*, 
               a.name as artist_name, a.avatar_url as artist_avatar,
               al.title as album_title, al.cover_url as album_cover
        FROM tracks t
        LEFT JOIN artists a ON t.artist_id = a.id
        LEFT JOIN albums al ON t.album_id = al.id
        ORDER BY t.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
      countResult = await sql`
        SELECT COUNT(*) as total FROM tracks t
      `
    }

    const total = Number.parseInt(countResult[0].total)

    return NextResponse.json({
      data: tracks,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    })
  } catch (error) {
    console.error("[v0] Get tracks error:", error)
    return NextResponse.json({ error: "Erreur lors de la récupération des pistes" }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const data = await request.json()

    const {
      title,
      artist_id,
      album_id,
      duration_ms,
      audio_url,
      cover_url,
      track_number,
      is_explicit,
      lyrics,
      status = "pending",
    } = data

    if (!title?.trim() || !artist_id || !audio_url) {
      return NextResponse.json({ error: "Champs requis manquants: title, artist_id, audio_url" }, { status: 400 })
    }

    if (title.length > 255) {
      return NextResponse.json({ error: "Le titre est trop long (max 255 caractères)" }, { status: 400 })
    }

    if (duration_ms && (duration_ms < 0 || duration_ms > 3600000)) {
      return NextResponse.json({ error: "Durée invalide (doit être entre 0 et 60 minutes)" }, { status: 400 })
    }

    const artistCheck = await sql`
      SELECT id, name FROM artists WHERE id = ${artist_id}
    `

    if (artistCheck.length === 0) {
      return NextResponse.json({ error: "Artiste non trouvé" }, { status: 404 })
    }

    if (album_id) {
      const albumCheck = await sql`
        SELECT id FROM albums WHERE id = ${album_id}
      `
      if (albumCheck.length === 0) {
        return NextResponse.json({ error: "Album non trouvé" }, { status: 404 })
      }
    }

    const tracks = await sql`
      INSERT INTO tracks (title, artist_id, album_id, duration_ms, audio_url, 
                         cover_url, track_number, is_explicit, lyrics, status)
      VALUES (${title.trim()}, ${artist_id}, ${album_id || null}, ${duration_ms || 0}, ${audio_url},
              ${cover_url || null}, ${track_number || null}, ${is_explicit || false}, ${lyrics || null}, ${status})
      RETURNING *
    `

    console.log("[v0] Track created:", { id: tracks[0].id, title: tracks[0].title })

    return NextResponse.json(tracks[0], { status: 201 })
  } catch (error) {
    console.error("[v0] Create track error:", error)
    return NextResponse.json({ error: "Erreur lors de la création de la piste" }, { status: 500 })
  }
}
