import { NextRequest, NextResponse } from 'next/server' import { requireAuth } from '@/lib/auth' import { getPlayHistory, updatePlayHistoryItem } from '@/lib/player' export async function GET(request: NextRequest) { try { const user = await requireAuth() const { searchParams } = new URL(request.url) const limit = parseInt(searchParams.get('limit') || '50') const offset = parseInt(searchParams.get('offset') || '0') // Validate pagination parameters if (limit < 1 || limit > 100) { return NextResponse.json( { error: 'Limit must be between 1 and 100' }, { status: 400 } ) } if (offset < 0) { return NextResponse.json( { error: 'Offset must be non-negative' }, { status: 400 } ) } const history = await getPlayHistory(user.id, limit, offset) return NextResponse.json( { history, limit, offset }, { status: 200 } ) } catch (error) { console.error('Get play history error:', error) if (error instanceof Error && error.message === 'Unauthorized') { return NextResponse.json( { error: 'Unauthorized' }, { status: 401 } ) } return NextResponse.json( { error: 'Failed to fetch play history' }, { status: 500 } ) } } export async function POST(request: NextRequest) { try { const user = await requireAuth() const body = await request.json() const { songId, playedDuration, completed } = body if (!songId) { return NextResponse.json( { error: 'Song ID is required' }, { status: 400 } ) } if (typeof playedDuration !== 'number' || playedDuration < 0) { return NextResponse.json( { error: 'Played duration must be a non-negative number' }, { status: 400 } ) } await updatePlayHistoryItem( user.id, songId, playedDuration, completed || false ) return NextResponse.json( { message: 'Play history updated' }, { status: 200 } ) } catch (error) { console.error('Update play history error:', error) if (error instanceof Error && error.message === 'Unauthorized') { return NextResponse.json( { error: 'Unauthorized' }, { status: 401 } ) } return NextResponse.json( { error: 'Failed to update play history' }, { status: 500 } ) } }