import { Router } from 'express'

import { uploadSingleFile } from '../file-upload.js'
import { uploadFileAsset } from '../../services/file-storage/file-storage-service.js'
import { createJsonHandler, getRequiredAdminSession, requireAdminRoles } from './session.js'

const router = Router()

router.post(
  '/files/upload',
  requireAdminRoles(['admin', 'operator', 'support']),
  uploadSingleFile,
  createJsonHandler(
    (req) => {
      const session = getRequiredAdminSession(req)
      return uploadFileAsset({
        file: req.file,
        scene: req.body?.scene,
        uploaderType: 'admin',
        uploaderId: String(session.userId || session.username || ''),
      })
    },
    {
      successMessage: '文件已上传',
      errorMessage: '文件上传失败',
      scope: '[admin/files/upload]',
      audit: (_req, data) => ({
        action: 'file_uploaded',
        targetType: 'file',
        targetId: String((data as { file?: { objectKey?: string } })?.file?.objectKey || ''),
        data: data && typeof data === 'object' ? (data as Record<string, unknown>) : {},
      }),
    },
  ),
)

export default router
