import { Router } from 'express'

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

const router = Router()

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

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

  logIntegration('[affiliate-dash/notify]', '收到 affiliate-dash 订单回调', {
    requestId,
    method: req.method,
    originalUrl: req.originalUrl,
    ip: req.ip,
    headers: {
      'content-type': req.headers['content-type'],
      'x-event-id': req.headers['x-event-id'],
      'x-timestamp': req.headers['x-timestamp'],
      'x-sign': req.headers['x-sign'],
    },
    rawBody: req.rawBody,
  })

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

export default router
