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

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

    if (!artistId) {
      return NextResponse.json({ error: "Artist ID required" }, { status: 400 })
    }

    const releases = await sql`
      SELECT * FROM scheduled_releases
      WHERE artist_id = ${artistId}
      ORDER BY release_date DESC
    `

    return NextResponse.json({ releases })
  } catch (error) {
    console.error("Error fetching releases:", error)
    return NextResponse.json({ error: "Failed to fetch releases" }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { artistId, title, releaseType, releaseDate, coverUrl, description } = body

    if (!artistId || !title || !releaseType || !releaseDate) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 })
    }

    const status = new Date(releaseDate) <= new Date() ? "released" : "scheduled"

    const result = await sql`
      INSERT INTO scheduled_releases (artist_id, title, release_type, release_date, cover_url, description, status)
      VALUES (${artistId}, ${title}, ${releaseType}, ${releaseDate}, ${coverUrl || null}, ${description || null}, ${status})
      RETURNING *
    `

    return NextResponse.json(result[0], { status: 201 })
  } catch (error) {
    console.error("Error creating release:", error)
    return NextResponse.json({ error: "Failed to create release" }, { status: 500 })
  }
}

export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json()
    const { id, status, title, releaseDate } = body

    if (!id) {
      return NextResponse.json({ error: "Release ID required" }, { status: 400 })
    }

    const result = await sql`
      UPDATE scheduled_releases
      SET 
        status = COALESCE(${status}, status),
        title = COALESCE(${title}, title),
        release_date = COALESCE(${releaseDate}, release_date)
      WHERE id = ${id}
      RETURNING *
    `

    return NextResponse.json(result[0])
  } catch (error) {
    console.error("Error updating release:", error)
    return NextResponse.json({ error: "Failed to update release" }, { status: 500 })
  }
}

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

    if (!id) {
      return NextResponse.json({ error: "Release ID required" }, { status: 400 })
    }

    await sql`DELETE FROM scheduled_releases WHERE id = ${id}`

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Error deleting release:", error)
    return NextResponse.json({ error: "Failed to delete release" }, { status: 500 })
  }
}
