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 { page, limit, offset } = getPaginationValues({
      page: Number.parseInt(searchParams.get("page") || "1"),
      limit: Number.parseInt(searchParams.get("limit") || "20"),
    })
    const search = searchParams.get("search") || ""
    const artistId = searchParams.get("artist_id")
    const status = searchParams.get("status")

    const whereConditions = []
    if (search) {
      whereConditions.push(`al.title ILIKE '%${search}%'`)
    }
    if (artistId) {
      whereConditions.push(`al.artist_id = '${artistId}'`)
    }
    if (status) {
      whereConditions.push(`al.status = '${status}'`)
    }

    const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(" AND ")}` : ""

    const albums = await sql`
      SELECT 
        al.*, 
        a.name as artist_name, 
        a.avatar_url as artist_avatar,
        (SELECT COUNT(*) FROM tracks t WHERE t.album_id = al.id) as track_count,
        (SELECT COALESCE(SUM(t.total_streams), 0) FROM tracks t WHERE t.album_id = al.id) as total_streams
      FROM albums al
      LEFT JOIN artists a ON al.artist_id = a.id
      ${sql.unsafe(whereClause)}
      ORDER BY al.release_date DESC NULLS LAST
      LIMIT ${limit} OFFSET ${offset}
    `

    const countResult = await sql`
      SELECT COUNT(*) as total FROM albums al ${sql.unsafe(whereClause)}
    `
    const total = Number.parseInt(countResult[0].total)

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

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

    const {
      title,
      artist_id,
      cover_url,
      release_date,
      album_type,
      label,
      copyright,
      is_explicit,
      status = "draft",
    } = data

    if (!title || !artist_id) {
      return NextResponse.json({ error: "Titre et artiste requis" }, { status: 400 })
    }

    const albums = await sql`
      INSERT INTO albums (title, artist_id, cover_url, release_date, album_type,
                         label, copyright, is_explicit, status)
      VALUES (${title}, ${artist_id}, ${cover_url}, ${release_date}, ${album_type || "album"},
              ${label}, ${copyright}, ${is_explicit || false}, ${status})
      RETURNING *
    `

    return NextResponse.json(albums[0], { status: 201 })
  } catch (error) {
    console.error("Create album error:", error)
    return NextResponse.json({ error: "Erreur lors de la création de l'album" }, { status: 500 })
  }
}
