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

export async function GET() {
  try {
    const playlists = await sql`
      SELECT 
        p.id, p.name, p.description, p.cover_url, p.is_public, p.created_at,
        p.total_tracks, p.total_followers,
        u.name as creator_name
      FROM playlists p
      LEFT JOIN users u ON p.user_id = u.id
      ORDER BY p.created_at DESC
    `

    return NextResponse.json({
      playlists: playlists.map((p: any) => ({
        id: p.id,
        title: p.name,
        cover: p.cover_url || "/placeholder.svg?height=100&width=100",
        creator: p.creator_name || "MusicApp",
        tracks: p.total_tracks || 0,
        followers: p.total_followers || 0,
        type: p.creator_name === "MusicApp" || !p.creator_name ? "editorial" : "user",
        visibility: p.is_public ? "public" : "private",
      })),
    })
  } catch (error) {
    console.error("Playlists error:", error)
    return NextResponse.json({ error: "Failed to fetch playlists" }, { status: 500 })
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { title, description, visibility } = body

    const result = await sql`
      INSERT INTO playlists (name, description, is_public, created_at, updated_at)
      VALUES (${title}, ${description}, ${visibility === "public"}, NOW(), NOW())
      RETURNING id
    `

    return NextResponse.json({ success: true, id: result[0].id })
  } catch (error) {
    console.error("Create playlist error:", error)
    return NextResponse.json({ error: "Failed to create playlist" }, { status: 500 })
  }
}
