import { Router } from 'express'

import { processAgisoTradeWebhook } from '../services/order/webhook-service.js'
import { createRequestId, logWebhook } from '../utils/logger.js'
import { buildNotFoundPayload, buildSuccessPayload, sendRouteError } from '../utils/http.js'

const router = Router()

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

  logWebhook('[webhooks/agiso/trade]', '收到 Agiso webhook 请求', {
    requestId,
    method: req.method,
    originalUrl: req.originalUrl,
    ip: req.ip,
    headers: req.headers,
    query: req.query,
    body: req.body,
  })

  try {
    const data = await processAgisoTradeWebhook({
      requestId,
      headers: req.headers,
      query: req.query,
      body: req.body,
    })

    logWebhook('[webhooks/agiso/trade]', 'Agiso webhook 处理完成', {
      requestId,
      durationMs: Date.now() - startedAt,
      result: data,
    })

    res.json(buildSuccessPayload(data, 'success'))
  } catch (error) {
    logWebhook(
      '[webhooks/agiso/trade]',
      'Agiso webhook 处理失败',
      {
        requestId,
        durationMs: Date.now() - startedAt,
        error,
      },
      { level: 'error' },
    )
    sendRouteError(res, error, '处理 Agiso 订单通知失败', '[webhooks/agiso/trade]')
  }
})

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

export default router
