import { NextApiRequest, NextApiResponse } from "next";
import _startWith from 'lodash/startsWith'
import { Readable } from 'node:stream'


export default async (req: NextApiRequest, res: NextApiResponse) => {
  if (req.method === 'GET') {
    try {
      const token = req.cookies.token
      const domainMedia = process.env.API_GATEWAY_MEDIA
      const urlString = req.query.url as string

      if (!_startWith(urlString, domainMedia)) {
        return res.status(401).send('Unauthorized')
      }

      const url = new URL(urlString)
      const path = url.pathname
      const targetUrl = `${process.env.API_GATEWAY?.replace('/api/v1', '')}${path}`
      const clientIp = req.headers['x-forwarded-for'] || req.socket?.remoteAddress
      const userAgent = req.headers['user-agent']

      const response = await fetch(targetUrl, {
        headers: {
          Authorization: `Bearer ${token}`,
          'X-Client-IP': clientIp === '::1' ? '127.0.0.1' : `${clientIp}`,
          'User-Agent': userAgent || ''
        }
      })

      if (!response.ok || !response.body) {
        return res.status(response.status).send(await response.text())
      }

      response.headers.forEach((value, key) => {
        res.setHeader(key, value)
      })

      const nodeStream = Readable.fromWeb(response.body as any)
      nodeStream.pipe(res)

    } catch (e) {
      console.error(e)
      return res.status(500).json({ error: 'Internal Server Error' })
    }
  } else {
    res.status(405).end()
  }
}