const moment = require('moment-jalaali')
const MessageModel = require('../models/MessageModel')
const UserModel = require('../models/UserModel')

function formatTimeOnly(date) {
  return moment(date).locale('fa').format('HH:mm:ss')
}

async function enrichMessage(message) {
  const doc = message._doc ? { ...message._doc } : { ...message }
  let replyTo = null

  if (doc.replyToId) {
    const parent = await MessageModel.findById(doc.replyToId).lean()
    if (parent) {
      const parentUser =
        String(parent.senderId) === String(doc.senderId)
          ? await UserModel.findById(doc.senderId).select('first_name last_name user_name').lean()
          : await UserModel.findById(parent.senderId).select('first_name last_name user_name').lean()
      replyTo = {
        _id: parent._id,
        content: (parent.content || 'پیام').slice(0, 200),
        senderName: parentUser
          ? `${parentUser.first_name || ''} ${parentUser.last_name || ''}`.trim() || parentUser.user_name
          : 'کاربر'
      }
    }
  }

  return {
    ...doc,
    createdAt: formatTimeOnly(doc.createdAt),
    replyTo,
    forwardedFrom: doc.forwardedFrom || undefined
  }
}

function emitChatEvents(io, message, senderId, receiverId) {
  const payload = message
  const roomA = `chat:${senderId}:${receiverId}`
  const roomB = `chat:${receiverId}:${senderId}`
  io.to(roomA).to(roomB).emit('newMessage', payload)
  io.to(`user:${senderId}`).to(`user:${receiverId}`).emit('chatListUpdate', {
    senderId,
    receiverId,
    message: payload
  })
}

function parseForwardedContent(content) {
  if (!content) return { body: '', forwardedFrom: null }
  try {
    const line = content.split('\n')[0]
    const j = JSON.parse(line)
    if (j.forwardedFrom) {
      return {
        forwardedFrom: j.forwardedFrom,
        body: content.replace(/^\{.*\}\n?/, '').trim()
      }
    }
  } catch (_) {
    /* not json */
  }
  return { body: content, forwardedFrom: null }
}

module.exports = {
  formatTimeOnly,
  enrichMessage,
  emitChatEvents,
  parseForwardedContent
}
