/**
 * 历史短链只读跳转入口（/s/:code）。
 * 新 claim 交付请使用本站 /#/claim/{token}，勿再为 feifei 生成 shortLink。
 */
import { Router } from 'express'

import { resolveShortLinkTarget } from '../services/short-links/short-link-service.js'
import { createRequestId, logIntegration } from '../utils/logger.js'
import { sendRouteError } from '../utils/http.js'

const router = Router()

router.get('/:code', async (req, res) => {
  const requestId = createRequestId('sl')
  const startedAt = Date.now()

  try {
    const row = await resolveShortLinkTarget(req.params.code)
    logIntegration('[short-link]', '短链跳转', {
      requestId,
      code: row.code,
      taskId: row.task_id || null,
      source: row.source,
      durationMs: Date.now() - startedAt,
    })
    res.redirect(302, row.target_url)
  } catch (error) {
    logIntegration(
      '[short-link]',
      '短链跳转失败',
      {
        requestId,
        code: req.params.code,
        durationMs: Date.now() - startedAt,
        error,
      },
      { level: 'warn' },
    )
    sendRouteError(res, error, '短链不可用', '[short-link]')
  }
})

export default router
