import { Router } from 'express'

import { createRateLimitMiddleware, getBodyFieldRateLimitKey } from '../middleware/rate-limit.js'
import {
  collectLookupWorkOrder,
  collectSubmitWorkOrder,
} from '../services/worker-platform/index.js'
import { uploadFileAsset } from '../services/file-storage/file-storage-service.js'
import { buildNotFoundPayload, createRouteHandler } from '../utils/http.js'
import { uploadSingleFile } from './file-upload.js'

const router = Router()

const collectRateLimit = createRateLimitMiddleware({
  scope: 'collect',
  windowMs: 60_000,
  max: 60,
  key: getBodyFieldRateLimitKey('orderNo'),
})

router.post(
  '/lookup',
  collectRateLimit,
  createRouteHandler((req) => collectLookupWorkOrder(req.body || {}), {
    successMessage: 'ok',
    errorMessage: '查询待完善订单失败',
    scope: '[collect/lookup]',
  }),
)

router.post(
  '/submit',
  collectRateLimit,
  createRouteHandler((req) => collectSubmitWorkOrder(req.body || {}), {
    successMessage: '资料已提交',
    errorMessage: '提交补充资料失败',
    scope: '[collect/submit]',
  }),
)

router.post(
  '/upload',
  collectRateLimit,
  uploadSingleFile,
  createRouteHandler(
    (req) => {
      return uploadFileAsset({
        file: req.file,
        scene: req.body?.scene || 'collect-material',
        uploaderType: 'collect',
        uploaderId: String(req.body?.orderNo || 'anonymous'),
      })
    },
    {
      successMessage: '文件已上传',
      errorMessage: '文件上传失败',
      scope: '[collect/upload]',
    },
  ),
)

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

export default router
