import { NextRequest, NextResponse } from 'next/server' import { prisma } from '@/lib/prisma' import { requireAuth } from '@/lib/auth' import { playSong, getNextInQueue } from '@/lib/player' export async function POST(request: NextRequest) { try { const user = await requireAuth() const body = await request.json() const { songId } = body // If a specific songId is provided, play that song if (songId) { // Verify the song exists and is public const song = await prisma.song.findUnique({ where: { id: songId }, select: { id: true, isPublic: true, artistId: true }, }) if (!song) { return NextResponse.json( { error: 'Song not found' }, { status: 404 } ) } if (!song.isPublic && song.artistId !== user.id) { return NextResponse.json( { error: 'Cannot play this song' }, { status: 403 } ) } await playSong(user.id, songId, 'manual') return NextResponse.json( { message: 'Playing song', songId }, { status: 200 } ) } // If no songId, play next in queue const nextSongId = await getNextInQueue(user.id) if (!nextSongId) { return NextResponse.json( { error: 'No songs in queue' }, { status: 404 } ) } await playSong(user.id, nextSongId, 'queue') return NextResponse.json( { message: 'Playing next song in queue', songId: nextSongId }, { status: 200 } ) } catch (error) { console.error('Play error:', error) if (error instanceof Error && error.message === 'Unauthorized') { return NextResponse.json( { error: 'Unauthorized' }, { status: 401 } ) } return NextResponse.json( { error: 'Failed to play song' }, { status: 500 } ) } }