111 lines
2.7 KiB
TypeScript
111 lines
2.7 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { requireAuth } from '@/lib/auth'
|
|
|
|
export async function POST(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const user = await requireAuth()
|
|
const { id } = await params
|
|
|
|
const playlist = await prisma.playlist.findUnique({
|
|
where: { id },
|
|
include: {
|
|
songs: {
|
|
orderBy: {
|
|
position: 'desc',
|
|
},
|
|
take: 1,
|
|
},
|
|
},
|
|
})
|
|
|
|
if (!playlist) {
|
|
return NextResponse.json({ error: 'Playlist not found' }, { status: 404 })
|
|
}
|
|
|
|
if (playlist.userId !== user.id) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 403 })
|
|
}
|
|
|
|
const body = await request.json()
|
|
const { songId } = body
|
|
|
|
if (!songId) {
|
|
return NextResponse.json({ error: 'songId is required' }, { status: 400 })
|
|
}
|
|
|
|
// Check if song exists
|
|
const song = await prisma.song.findUnique({
|
|
where: { id: songId },
|
|
})
|
|
|
|
if (!song) {
|
|
return NextResponse.json({ error: 'Song not found' }, { status: 404 })
|
|
}
|
|
|
|
// Check if song is already in playlist
|
|
const existingPlaylistSong = await prisma.playlistSong.findUnique({
|
|
where: {
|
|
playlistId_songId: {
|
|
playlistId: id,
|
|
songId,
|
|
},
|
|
},
|
|
})
|
|
|
|
if (existingPlaylistSong) {
|
|
return NextResponse.json({ error: 'Song already in playlist' }, { status: 400 })
|
|
}
|
|
|
|
// Get the next position
|
|
const nextPosition = playlist.songs.length > 0 ? playlist.songs[0].position + 1 : 0
|
|
|
|
const playlistSong = await prisma.playlistSong.create({
|
|
data: {
|
|
playlistId: id,
|
|
songId,
|
|
position: nextPosition,
|
|
},
|
|
include: {
|
|
song: {
|
|
include: {
|
|
artist: {
|
|
select: {
|
|
id: true,
|
|
name: true,
|
|
slug: true,
|
|
avatarUrl: true,
|
|
verified: true,
|
|
},
|
|
},
|
|
album: {
|
|
select: {
|
|
id: true,
|
|
title: true,
|
|
slug: true,
|
|
coverUrl: true,
|
|
},
|
|
},
|
|
genres: {
|
|
include: {
|
|
genre: true,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
})
|
|
|
|
return NextResponse.json(playlistSong, { status: 201 })
|
|
} catch (error) {
|
|
if (error instanceof Error && error.message === 'Unauthorized') {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
console.error('Error adding song to playlist:', error)
|
|
return NextResponse.json({ error: 'Failed to add song to playlist' }, { status: 500 })
|
|
}
|
|
}
|