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

async function searchActivities(args = {}) {
  const res = await request('/ai/activities/search', {
    method: 'GET',
    data: {
      keyword: args.keyword,
      branchId: args.branchId,
      dateRange: args.dateRange || 'FUTURE',
      onlyRegisterable: !!args.onlyRegisterable,
      limit: args.limit || 5
    },
    skillName: 'activity'
  })

  if (res.error) {
    return {
      isError: true,
      content: [{ type: 'text', text: res.safeMessage || '活动查询失败，请稍后重试。' }]
    }
  }

  const data = res.data || {}
  const sourceItems = data.items || []
  const items = sourceItems.map((item) => ({
    activityId: item.activityId,
    title: item.title,
    branchName: item.branchName,
    startTime: item.startTime,
    endTime: item.endTime,
    location: item.location,
    status: item.status,
    registerable: !!item.registerable,
    registerButtonText: item.registerButtonText || (item.registerable ? '可报名' : '查看详情'),
    remainingSeats: item.remainingSeats
  }))

  return {
    isError: false,
    content: [{ type: 'text', text: `已找到 ${items.length} 个活动。请展示活动列表卡片，等待用户选择具体活动。` }],
    structuredContent: {
      items,
      total: data.total || items.length,
      hasMore: !!data.hasMore
    },
    _meta: {
      viewItems: sourceItems,
      relatedPage: '/pages/events/index'
    }
  }
}

module.exports = searchActivities
