import { Router } from 'express'

import { createRateLimitMiddleware } from '../middleware/rate-limit.js'
import { handleKuaishouFeifeiNotify } from '../services/platforms/kuaishou-feifei/notify-service.js'
import { createRequestId, logIntegration } from '../utils/logger.js'
import { sendRouteError } from '../utils/http.js'

const router = Router()

const notifyRateLimit = createRateLimitMiddleware({
  scope: 'kuaishouFeifeiNotify',
  windowMs: 60_000,
  max: 300,
})

router.post('/notify', notifyRateLimit, async (req, res) => {
  const requestId = createRequestId('ffn')
  const startedAt = Date.now()

  logIntegration('[kuaishou-feifei/notify]', '收到 kuaishou-feifei 订单通知', {
    requestId,
    method: req.method,
    originalUrl: req.originalUrl,
    ip: req.ip,
    headers: {
      'content-type': req.headers['content-type'],
      'x-app-key': req.headers['x-app-key'],
      'x-timestamp': req.headers['x-timestamp'],
      'x-sign': req.headers['x-sign'],
    },
    body: req.body,
    rawBody: req.rawBody,
  })

  try {
    const result = await handleKuaishouFeifeiNotify({
      body: req.body,
      headers: req.headers,
      rawBody: req.rawBody,
    })
    logIntegration('[kuaishou-feifei/notify]', '订单通知处理完成', {
      requestId,
      durationMs: Date.now() - startedAt,
      result,
    })
    res.status(200).json({ code: 0 })
  } catch (error) {
    logIntegration(
      '[kuaishou-feifei/notify]',
      '订单通知处理失败',
      {
        requestId,
        durationMs: Date.now() - startedAt,
        error,
      },
      { level: 'error' },
    )
    sendRouteError(res, error, 'kuaishou-feifei 通知处理失败', '[kuaishou-feifei/notify]')
  }
})

export default router
