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

// Bulk import tracks for an album
export async function POST(request: NextRequest) {
  try {
    const adminId = await getAdminUser(request)
    if (!adminId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }

    const body = await request.json()
    const { tracks, album_id, artist_id } = body

    if (!Array.isArray(tracks) || tracks.length === 0) {
      return NextResponse.json({ error: "No tracks provided" }, { status: 400 })
    }

    const results = []

    for (let i = 0; i < tracks.length; i++) {
      const track = tracks[i]
      try {
        const result = await sql`
          INSERT INTO tracks (
            title, artist_id, album_id, genre_id, duration,
            audio_url, cover_url, track_number, is_explicit, status
          ) VALUES (
            ${track.title}, 
            ${track.artist_id || artist_id || null}, 
            ${track.album_id || album_id || null}, 
            ${track.genre_id || null}, 
            ${track.duration || 0},
            ${track.audio_url || null}, 
            ${track.cover_url || null}, 
            ${track.track_number || i + 1},
            ${track.is_explicit || false},
            ${track.status || "published"}
          )
          RETURNING *
        `
        results.push({ success: true, track: result[0] })
      } catch (error) {
        results.push({ success: false, error: String(error), track: track.title })
      }
    }

    const successful = results.filter((r) => r.success).length
    const failed = results.filter((r) => !r.success).length

    return NextResponse.json({
      message: `Imported ${successful} tracks, ${failed} failed`,
      results,
      stats: { successful, failed, total: tracks.length },
    })
  } catch (error) {
    console.error("Error bulk importing tracks:", error)
    return NextResponse.json({ error: "Failed to bulk import tracks" }, { status: 500 })
  }
}
