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

async function prepareActivityRegistration({ activityId } = {}) {
  if (!activityId) {
    return {
      isError: true,
      content: [{ type: 'text', text: '缺少 activityId。请先让用户从活动列表或详情卡中选择活动。' }]
    }
  }

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

  const data = res.data || {}
  if (res.error) {
    return {
      isError: false,
      content: [{ type: 'text', text: res.safeMessage || '当前活动暂时不能报名。' }],
      structuredContent: {
        activityId,
        canRegister: false,
        confirmText: res.safeMessage || '当前活动暂时不能报名'
      },
      _meta: {
        status: 'blocked',
        reason: res.error.code,
        nextAction: res.uiHints && res.uiHints.nextAction
      }
    }
  }

  return {
    isError: false,
    content: [{ type: 'text', text: '报名资格预检查已通过。请展示报名确认卡，等待用户点击确认。' }],
    structuredContent: {
      activityId: data.activityId || activityId,
      canRegister: !!data.canRegister,
      confirmToken: data.confirmToken,
      confirmExpiresAt: data.confirmExpiresAt,
      confirmText: data.confirmText,
      activity: data.activity
    },
    _meta: {
      activity: data.activity,
      confirmToken: data.confirmToken
    }
  }
}

module.exports = prepareActivityRegistration
