const { request } = require('../utils/request.js')

async function confirmActivityRegistration({ activityId, confirmToken } = {}) {
  if (!activityId || !confirmToken) {
    return {
      isError: true,
      content: [{ type: 'text', text: '缺少 activityId 或 confirmToken。请先调用 prepareActivityRegistration 并等待用户点击确认卡。' }]
    }
  }

  const res = await request(`/ai/activities/${encodeURIComponent(activityId)}/register`, {
    method: 'POST',
    data: { confirmToken, source: 'WECHAT_AI_SKILL' },
    skillName: 'activity'
  })

  if (res.error) {
    return {
      isError: false,
      content: [{ type: 'text', text: res.safeMessage || '报名没有成功，请展示失败状态。' }],
      structuredContent: {
        success: false,
        message: res.safeMessage || '报名没有成功',
        errorCode: res.error.code
      },
      _meta: {
        status: 'failed',
        uiHints: res.uiHints || {}
      }
    }
  }

  const data = res.data || {}
  return {
    isError: false,
    content: [{ type: 'text', text: `报名成功。凭证号为 ${data.voucherCode || '已生成'}。` }],
    structuredContent: {
      success: true,
      registrationId: data.registrationId,
      voucherCode: data.voucherCode,
      pointsAwarded: data.pointsAwarded,
      relatedPage: data.relatedPage
    },
    _meta: {
      status: 'success',
      relatedPage: data.relatedPage
    }
  }
}

module.exports = confirmActivityRegistration
