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 
        ac.*,
        t.title as track_title,
        t.cover_url as track_cover
      FROM artist_campaigns ac
      LEFT JOIN tracks t ON ac.track_id = t.id
      WHERE ac.artist_id = ${artistId}
      ORDER BY ac.created_at DESC
    `

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

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

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

    const result = await sql`
      INSERT INTO artist_campaigns (artist_id, track_id, title, objective, budget, start_date, end_date, status)
      VALUES (
        ${artistId}, 
        ${trackId || null}, 
        ${title}, 
        ${objective || "streams"}, 
        ${Number.parseInt(budget) || 0}, 
        ${startDate}, 
        ${endDate},
        ${new Date(startDate) <= new Date() ? "active" : "scheduled"}
      )
      RETURNING *
    `

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

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

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

    const result = await sql`
      UPDATE artist_campaigns
      SET status = ${status}
      WHERE id = ${id}
      RETURNING *
    `

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

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

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