export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { getAccessToken } from '@/lib/spotify-client'

async function spotifyFetch(path: string, method = 'GET', body?: any) {
  const token = await getAccessToken()
  const res = await fetch(`https://api.spotify.com/v1${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${token}`,
      ...(body ? { 'Content-Type': 'application/json' } : {}),
    },
    ...(body ? { body: JSON.stringify(body) } : {}),
  })
  if (res.status === 204) return { success: true }
  if (!res.ok) {
    const err = await res.text()
    // Специальная обработка: нет активного устройства
    if (res.status === 404 && err.includes('NO_ACTIVE_DEVICE')) {
      throw Object.assign(new Error('NO_ACTIVE_DEVICE'), { code: 'NO_ACTIVE_DEVICE' })
    }
    throw new Error(`Spotify API ${res.status}: ${err}`)
  }
  return res.json().catch(() => ({ success: true }))
}

export async function GET() {
  try {
    // Get current playback state
    const data = await spotifyFetch('/me/player')
    if (!data || !data.item) return NextResponse.json({ playing: false })
    return NextResponse.json({
      playing: data.is_playing,
      track: data.item.name,
      artist: data.item.artists?.map((a: any) => a.name).join(', '),
      album: data.item.album?.name,
      volume: data.volume_percent,
      device: data.device?.name,
    })
  } catch (e: any) {
    if (e?.code === 'NO_ACTIVE_DEVICE' || e?.message === 'NO_ACTIVE_DEVICE') {
      return NextResponse.json({ error: 'no_active_device', message: 'Нет активного устройства Spotify. Открой Spotify на телефоне или ноутбуке.' }, { status: 200 })
    }
    return NextResponse.json({ error: String(e?.message || e) }, { status: 500 })
  }
}

export async function POST(req: NextRequest) {
  const body = await req.json()
  const { action, query, volume } = body

  try {
  switch (action) {
    case 'play':
      if (query) {
        // Search first
        const search = await spotifyFetch(`/search?q=${encodeURIComponent(query)}&type=track,artist,playlist&limit=1`)
        const track = search.tracks?.items?.[0]
        const artist = search.artists?.items?.[0]
        if (track) {
          await spotifyFetch('/me/player/play', 'PUT', { uris: [track.uri] })
          return NextResponse.json({ success: true, playing: track.name, artist: track.artists?.[0]?.name })
        } else if (artist) {
          // Play top tracks of artist
          const top = await spotifyFetch(`/artists/${artist.id}/top-tracks?market=RU`)
          const uris = top.tracks?.slice(0, 10).map((t: any) => t.uri) || []
          await spotifyFetch('/me/player/play', 'PUT', { uris })
          return NextResponse.json({ success: true, playing: `${artist.name} — топ треки` })
        }
        return NextResponse.json({ error: 'not found' }, { status: 404 })
      } else {
        await spotifyFetch('/me/player/play', 'PUT')
        return NextResponse.json({ success: true })
      }
    case 'pause':
      await spotifyFetch('/me/player/pause', 'PUT')
      return NextResponse.json({ success: true })
    case 'next':
      await spotifyFetch('/me/player/next', 'POST')
      return NextResponse.json({ success: true })
    case 'previous':
      await spotifyFetch('/me/player/previous', 'POST')
      return NextResponse.json({ success: true })
    case 'volume':
      await spotifyFetch(`/me/player/volume?volume_percent=${Math.min(100, Math.max(0, volume || 50))}`, 'PUT')
      return NextResponse.json({ success: true, volume })
    default:
      return NextResponse.json({ error: 'unknown action' }, { status: 400 })
  }
  } catch (e: any) {
    if (e?.code === 'NO_ACTIVE_DEVICE' || e?.message === 'NO_ACTIVE_DEVICE') {
      return NextResponse.json({ error: 'no_active_device', message: 'Нет активного устройства Spotify. Открой Spotify на телефоне или ноутбуке.' }, { status: 200 })
    }
    return NextResponse.json({ error: String(e?.message || e) }, { status: 500 })
  }
}
