const MIZIK_URL = process.env.NEXT_PUBLIC_OKI_MIZIK_URL || 'https://funkwhale-server.com'
const MIZIK_API_USER = process.env.MIZIK_API_USER || 'user'
const MIZIK_API_PASSWORD = process.env.MIZIK_API_PASSWORD || 'password'

const FORWARDED_HEADERS = ['content-type', 'content-length', 'content-range', 'accept-ranges']

export async function GET(request, props) {
  const {id} = await props.params

  const upstreamUrl = `${MIZIK_URL}/rest/stream?u=${encodeURIComponent(MIZIK_API_USER)}&p=${encodeURIComponent(MIZIK_API_PASSWORD)}&id=${encodeURIComponent(id)}`
  const range = request.headers.get('range')

  const upstreamResponse = await fetch(upstreamUrl, {
    headers: range ? {range} : {}
  })

  const headers = new Headers()
  for (const key of FORWARDED_HEADERS) {
    const value = upstreamResponse.headers.get(key)
    if (value) {
      headers.set(key, value)
    }
  }

  return new Response(upstreamResponse.body, {
    status: upstreamResponse.status,
    headers
  })
}
