import { Router } from 'express'

import { createRateLimitMiddleware } from '../middleware/rate-limit.js'
import { createOpen91Order } from '../services/open-91/order-create-service.js'
import { queryOpen91Order } from '../services/open-91/order-query-service.js'
import { buildOpen91ErrorResponse } from '../services/open-91/response.js'
import { createRequestId, logIntegration } from '../utils/logger.js'

const router = Router()
const open91RateLimit = createRateLimitMiddleware({
  scope: 'open91',
  windowMs: 60_000,
  max: 120,
  onLimit: (_req, res) => {
    res.status(200).json(buildOpen91ErrorResponse('请求过于频繁，请稍后再试', 429))
  },
})

function resolveErrorStatusCode(error: unknown): number {
  if (!error || typeof error !== 'object' || !('statusCode' in error)) {
    return 500
  }

  return Number(error.statusCode || 500)
}

router.post('/orders/create', open91RateLimit, async (req, res) => {
  const requestId = createRequestId('91')
  const startedAt = Date.now()

  logIntegration('[open-91/create]', '收到 91卡券异步下单请求', {
    requestId,
    method: req.method,
    originalUrl: req.originalUrl,
    ip: req.ip,
    body: req.body,
  })

  try {
    const result = await createOpen91Order(req.body, { requestId })
    logIntegration('[open-91/create]', '91卡券异步下单处理完成', {
      requestId,
      durationMs: Date.now() - startedAt,
      result,
    })
    res.status(200).json(result)
  } catch (error) {
    const message = error instanceof Error ? error.message : '系统错误'
    const code = resolveErrorStatusCode(error) >= 500 ? 500 : 400
    logIntegration(
      '[open-91/create]',
      '91卡券异步下单处理失败',
      {
        requestId,
        durationMs: Date.now() - startedAt,
        error,
      },
      { level: 'error' },
    )
    res.status(200).json(buildOpen91ErrorResponse(message, code))
  }
})

router.post('/orders/query', open91RateLimit, async (req, res) => {
  const requestId = createRequestId('91')
  const startedAt = Date.now()

  logIntegration('[open-91/query]', '收到 91卡券订单查询请求', {
    requestId,
    method: req.method,
    originalUrl: req.originalUrl,
    ip: req.ip,
    body: req.body,
  })

  try {
    const result = await queryOpen91Order(req.body, { requestId })
    logIntegration('[open-91/query]', '91卡券订单查询处理完成', {
      requestId,
      durationMs: Date.now() - startedAt,
      result,
    })
    res.status(200).json(result)
  } catch (error) {
    const message = error instanceof Error ? error.message : '系统错误'
    const code = resolveErrorStatusCode(error) >= 500 ? 500 : 400
    logIntegration(
      '[open-91/query]',
      '91卡券订单查询处理失败',
      {
        requestId,
        durationMs: Date.now() - startedAt,
        error,
      },
      { level: 'error' },
    )
    res.status(200).json(buildOpen91ErrorResponse(message, code))
  }
})

export default router
