import { Router } from 'express'

import {
  replayAdminWebhookEvent,
} from '../../services/admin/admin-write-service.js'
import {
  getAdminWebhookEventDetail,
  getAdminWebhookEvents,
} from '../../services/admin/admin-read-service.js'
import { createJsonHandler, requireAdminRoles } from './shared.js'
import type {
  AdminWebhookEventRouteParams,
  AdminWebhookEventRouteQuery,
} from '../../types/admin-route-inputs.js'
import type { AdminWebhookReplayResponse } from '../../types/admin-write-models.js'

const router = Router()

router.use('/webhook-events', requireAdminRoles(['admin', 'operator']))

router.get('/webhook-events', createJsonHandler(
  (req) => getAdminWebhookEvents(req.query as AdminWebhookEventRouteQuery),
  {
    successMessage: 'ok',
    errorMessage: '读取 webhook 列表失败',
    scope: '[admin/webhook-events]',
  },
))

router.get('/webhook-events/:eventId', createJsonHandler(
  (req) => getAdminWebhookEventDetail((req.params as AdminWebhookEventRouteParams).eventId),
  {
    successMessage: 'ok',
    errorMessage: '读取 webhook 详情失败',
    scope: '[admin/webhook-events/:eventId]',
  },
))

router.post('/webhook-events/:eventId/replay', requireAdminRoles(['admin']), createJsonHandler(
  (req) => replayAdminWebhookEvent((req.params as AdminWebhookEventRouteParams).eventId),
  {
    successMessage: 'Webhook 已重放',
    errorMessage: '重放 webhook 失败',
    scope: '[admin/webhook-events/:eventId/replay]',
    audit: (req, data) => {
      const result = data as AdminWebhookReplayResponse
      return {
        action: 'webhook_replayed',
        targetType: 'webhook_event',
        targetId: String((req.params as AdminWebhookEventRouteParams).eventId),
        data: {
          eventId: result.eventId,
          replayed: result.replayed,
        },
      }
    },
  },
))

export default router
