import { NextResponse } from 'next/server'
import { navidromeGet } from '@/lib/navidrome'

interface SubsonicSong {
  id: string
  title: string
  artist: string
  album: string
  albumId: string
  duration: number
  track: number
  year: number
  coverArt: string
  suffix: string
}

interface PlaylistResult {
  playlist?: {
    id: string
    name: string
    songCount: number
    coverArt: string
    entry?: SubsonicSong[]
  }
}

export async function GET(
  _request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params

  try {
    const data = await navidromeGet<PlaylistResult>('getPlaylist.view', { id })
    const pl = data.playlist
    if (!pl) return NextResponse.json({ error: 'Playlist not found' }, { status: 404 })

    // Dedup by title+artist, keeping first occurrence
    const seen = new Set<string>()
    const songs = (pl.entry || []).reduce<Array<{
      id: string; title: string; artist: string; album: string; albumId: string;
      duration: number; track: number; year: number; coverArt: string; suffix: string;
    }>>((acc, s) => {
      const key = `${s.title.toLowerCase().trim()}|||${s.artist.toLowerCase().trim()}`
      if (!seen.has(key)) {
        seen.add(key)
        acc.push({
          id: s.id, title: s.title, artist: s.artist, album: s.album,
          albumId: s.albumId, duration: s.duration, track: s.track,
          year: s.year, coverArt: s.coverArt, suffix: s.suffix,
        })
      }
      return acc
    }, [])

    return NextResponse.json({
      id: pl.id,
      name: pl.name,
      songCount: pl.songCount,
      coverArt: pl.coverArt,
      songs,
    })
  } catch (error) {
    console.error('Get playlist error:', error)
    return NextResponse.json({ error: 'Failed to load playlist' }, { status: 502 })
  }
}

export async function POST(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params

  try {
    const { songId } = await request.json()
    if (!songId) {
      return NextResponse.json({ error: 'songId required' }, { status: 400 })
    }

    await navidromeGet('updatePlaylist.view', {
      playlistId: id,
      songIdToAdd: songId,
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Add to playlist error:', error)
    return NextResponse.json({ error: 'Failed to add to playlist' }, { status: 502 })
  }
}
