import { Router } from 'express'

import { getStoredFileObject } from '../services/file-storage/file-storage-service.js'
import { buildNotFoundPayload, sendRouteError } from '../utils/http.js'

const router = Router()

router.get('/object', async (req, res) => {
  try {
    const object = await getStoredFileObject(req.query.key, req.query.variant, {
      expires: req.query.expires,
      signature: req.query.signature,
    })
    res.setHeader('Content-Type', object.contentType || 'application/octet-stream')
    res.setHeader('Cache-Control', 'private, max-age=300')
    res.setHeader('X-Content-Type-Options', 'nosniff')
    object.reader.on('error', (error) => {
      if (!res.headersSent) {
        sendRouteError(res, error, '读取文件失败', '[files/object]')
      } else {
        res.destroy(error)
      }
    })
    object.reader.pipe(res)
  } catch (error) {
    sendRouteError(res, error, '读取文件失败', '[files/object]')
  }
})

router.use((req, res) => {
  res.status(404).json(buildNotFoundPayload(req))
})

export default router
