/** 会话列表展示：私聊固定显示对方昵称/头像，避免来回变成自己的 */
import { resolveAvatarUrl } from './avatar.js';
import { getLocalImUserId } from './im-user.js';

function getLocalDisplayName(app) {
  app = app || getApp();
  return (
    wx.getStorageSync('nicheng')
    || app.globalData.dashouNicheng
    || app.globalData.nicheng
    || ''
  );
}

function isLikelySelfProfile(name, avatar, app) {
  const myName = getLocalDisplayName(app);
  if (myName && name && name === myName) return true;
  const myTx = wx.getStorageSync('touxiang') || '';
  if (!myTx || !avatar) return false;
  const a = String(avatar);
  const t = String(myTx);
  return a.includes(t) || t.includes(a.replace(/^https?:\/\/[^/]+/, ''));
}

function stripImPrefix(id) {
  if (!id) return '';
  return String(id).replace(/^(Ds|Sj|Boss|Gs|Zz|Kh)/, '') || id;
}

export function normalizeConversationItem(item, app, peerCache = {}) {
  if (!item) return item;
  if (!item.data) item.data = {};

  if (item.type === 'private' && item.userId) {
    const peerId = item.userId;
    const lastMsg = item.lastMessage;
    let peerName = '';
    let peerAvatar = '';

    if (lastMsg && lastMsg.senderId === peerId && lastMsg.senderData) {
      peerName = lastMsg.senderData.name || '';
      peerAvatar = lastMsg.senderData.avatar || '';
    }

    if (peerCache[peerId]) {
      if (!peerName) peerName = peerCache[peerId].name || '';
      if (!peerAvatar) peerAvatar = peerCache[peerId].avatar || '';
    }

    if (item.data.name && !isLikelySelfProfile(item.data.name, item.data.avatar, app)) {
      if (!peerName) peerName = item.data.name;
      if (!peerAvatar) peerAvatar = item.data.avatar || '';
    }

    if (!peerName || isLikelySelfProfile(peerName, peerAvatar, app)) {
      peerName = stripImPrefix(peerId) || peerId;
    }

    item.data.name = peerName;
    item.data.avatar = resolveAvatarUrl(peerAvatar, app);
    item.key = 'private_' + peerId;

    if (peerName && !isLikelySelfProfile(peerName, peerAvatar, app)) {
      peerCache[peerId] = { name: peerName, avatar: peerAvatar };
    }
  } else if (item.type === 'group') {
    item.data.avatar = resolveAvatarUrl(item.data.avatar, app);
    if (!item.data.name) {
      item.data.name = item.data.orderId || item.groupId || '订单群聊';
    }
    item.key = 'group_' + (item.groupId || item.data.orderId || '');
  } else if (item.type === 'cs') {
    item.data.avatar = resolveAvatarUrl(item.data.avatar, app);
    if (!item.data.name) item.data.name = '在线客服';
    item.key = 'cs_' + (item.teamId || 'default');
  } else {
    item.key = item.userId || item.groupId || String(item.lastMessage?.timestamp || Math.random());
  }

  return item;
}

export function normalizeConversationsList(conversations, app, peerCache) {
  return (conversations || []).map((c) => normalizeConversationItem(c, app, peerCache));
}
