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 campaigns = await sql`
      SELECT * FROM promotions 
      WHERE is_active = true
      ORDER BY created_at DESC
      LIMIT 10
    `

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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { artistId, name, trackId, budget, startDate, endDate, objective } = body

    const result = await sql`
      INSERT INTO promotions (title, image_url, action_url, start_date, end_date, target_type, position, is_active)
      VALUES (${name}, '', '', ${startDate}, ${endDate}, ${objective || "track"}, 'banner', true)
      RETURNING *
    `

    return NextResponse.json(result[0])
  } catch (error) {
    console.error("Error creating promotion:", error)
    return NextResponse.json({ error: "Failed to create promotion" }, { 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: "Promotion ID required" }, { status: 400 })
    }

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

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