import {
  createTextMessage,
  createImageMessage,
  createVideoMessage,
  createFileMessage,
  createVoiceMessage
} from '@/utils/parent-message-factory'

function normalizeUserMeta(userMeta = {}) {
  return {
    direction: userMeta.direction || 'right',
    department: userMeta.department || '家长',
    name: userMeta.name || '我'
  }
}

export function buildTextOutgoingMessage(text, userMeta = {}) {
  const content = (text || '').trim()
  if (!content) return null
  return createTextMessage({
    ...normalizeUserMeta(userMeta),
    content,
    showReceiptToggle: true
  })
}

export async function pickImageOutgoingMessages(userMeta = {}) {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 9,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: (res) => {
        const messages = (res.tempFilePaths || []).map((imageUrl) =>
          createImageMessage({ ...normalizeUserMeta(userMeta), imageUrl })
        )
        resolve(messages)
      },
      fail: reject
    })
  })
}

export async function shootImageOutgoingMessage(userMeta = {}) {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: (res) => {
        const first = (res.tempFilePaths || [])[0]
        resolve(first ? createImageMessage({ ...normalizeUserMeta(userMeta), imageUrl: first }) : null)
      },
      fail: reject
    })
  })
}

export async function pickVideoOutgoingMessage(userMeta = {}) {
  return new Promise((resolve, reject) => {
    uni.chooseVideo({
      sourceType: ['camera', 'album'],
      compressed: true,
      maxDuration: 60,
      success: (res) => {
        const videoUrl = res.tempFilePath || ''
        if (!videoUrl) return resolve(null)
        const duration = Number.isFinite(res.duration)
          ? `${String(Math.floor(res.duration / 60)).padStart(2, '0')}:${String(Math.floor(res.duration % 60)).padStart(2, '0')}`
          : ''
        resolve(
          createVideoMessage({
            ...normalizeUserMeta(userMeta),
            videoUrl,
            coverUrl: res.thumbTempFilePath || '/static/logo.png',
            duration
          })
        )
      },
      fail: reject
    })
  })
}

export async function pickFileOutgoingMessage(userMeta = {}) {
  if (!uni.chooseMessageFile) {
    return null
  }
  return new Promise((resolve, reject) => {
    uni.chooseMessageFile({
      count: 1,
      type: 'file',
      success: (res) => {
        const file = (res.tempFiles || [])[0]
        if (!file) return resolve(null)
        resolve(
          createFileMessage({
            ...normalizeUserMeta(userMeta),
            fileName: file.name || '未命名文件',
            fileUrl: file.path || ''
          })
        )
      },
      fail: reject
    })
  })
}

export function buildVoiceOutgoingMessage({
  durationSeconds = 0,
  audioUrl = '',
  voiceText = ''
} = {}, userMeta = {}) {
  const safeDuration = Math.max(1, Math.floor(durationSeconds || 0))
  return createVoiceMessage({
    ...normalizeUserMeta(userMeta),
    duration: String(safeDuration),
    audioUrl,
    voicePreview: '语音消息',
    voiceText
  })
}
