import { getWebhookEventById } from '../../../repositories/webhook-event-repo.js'
import { replayAgisoTradeWebhookEvent } from '../../order/webhook-service.js'
import { createHttpError } from '../../../utils/http.js'

import type { AdminEntityIdInput } from '../../../types/admin-read-inputs.js'
import type { AdminWebhookReplayResponse } from '../../../types/admin-write-models.js'

export async function replayAdminWebhookEvent(eventId: AdminEntityIdInput): Promise<AdminWebhookReplayResponse> {
  const event = await getWebhookEventById(Number(eventId))

  if (!event) {
    throw createHttpError('Webhook 事件不存在', {
      statusCode: 404,
      errorCode: 'admin_webhook_not_found',
    })
  }

  if (String(event.provider || event.platform || '').trim() !== 'agiso') {
    throw createHttpError('当前只支持重放 agiso webhook', {
      statusCode: 409,
      errorCode: 'admin_webhook_replay_not_supported',
    })
  }

  const result = await replayAgisoTradeWebhookEvent(event)

  return {
    eventId: event.id,
    replayed: true,
    result,
  }
}
