const { apiError, apiSuccess, requestAssist } = require('./requestAssist.js')

const DRAFT_PREFIX = 'dlbdi-mini:ai-lead-draft:'

function createDraftKey() {
  return `${Date.now()}-${Math.random().toString(16).slice(2)}`
}

function storeDraft(draft) {
  if (!draft) return ''
  const draftKey = createDraftKey()
  try {
    wx.setStorageSync(`${DRAFT_PREFIX}${draftKey}`, {
      ...draft,
      createdAt: new Date().toISOString(),
      source: 'wechat_ai_skill',
    })
    return draftKey
  } catch (error) {
    console.warn('[prepareLeadDraft] failed to store draft', error)
    return ''
  }
}

function withDraftKey(result) {
  const draftKey = storeDraft(result.draft)
  if (!draftKey || !result.draft) return result
  const url = `${result.draft.pagePath}?aiDraftKey=${encodeURIComponent(draftKey)}`
  return {
    ...result,
    draft: {
      ...result.draft,
      draftKey,
      actionUrl: url,
    },
    actions: (result.actions || []).map((action, index) => index === 0 ? { ...action, url } : action),
  }
}

async function prepareLeadDraft({ leadType = 'consulting', message = '', payload = {} } = {}) {
  try {
    const result = await requestAssist({
      intent: 'prepareLeadDraft',
      leadType,
      message,
      payload,
    })
    const stored = withDraftKey(result)
    return apiSuccess(stored, stored.reply || '已整理申请草稿，请打开页面核对后手动提交。')
  } catch (error) {
    return apiError(error, '申请草稿整理失败')
  }
}

module.exports = prepareLeadDraft
