import { parseSenderPrefix } from './sender_parser.js';
import type { MessageRow } from './message_repo.js';
import type { ContactIdentity, RoomInfo } from './room_resolver.js';
import type { ArchiveMessage } from './archive_types.js';

/**
 * 把 MessageRepo 读到的 row 投影成 archive 写入行。
 *
 * - 群消息文本会带 "wxid_xxx:\n<body>" 前缀,需拆出 senderWxid 与 body
 * - 非文本/系统消息无前缀 → content 保留原值, senderWxid 为 null
 * - serverId 为 BigInt, 序列化为 string 以保留精度 (JS number 在 2^53 之后失精)
 * - rawHex 当前总是 null (content 字段已承载文本/XML); 预留给未来的二进制 blob 场景
 */
export function projectToArchive(
  row: MessageRow,
  channelId: number,
  room: RoomInfo,
  resolveContact?: (username: string) => ContactIdentity | undefined,
  resolveRoomSenderIdentity?: (roomUsername: string, realSenderId: string) => ContactIdentity | undefined,
): ArchiveMessage {
  const parsed = parseSenderPrefix(row.content);
  const parsedSenderWxid = parsed?.senderWxid ?? null;
  const contact = parsedSenderWxid
    ? resolveContact?.(parsedSenderWxid)
    : row.realSenderId != null
      ? resolveRoomSenderIdentity?.(room.username, String(row.realSenderId))
      : undefined;
  const senderWxid = parsedSenderWxid ?? contact?.username ?? null;
  return {
    channelId,
    roomId: room.username,
    roomName: room.roomName ?? null,
    msgTable: row.tableName,
    localId: row.localId,
    serverId: row.serverId != null ? row.serverId.toString() : null,
    localType: row.localType,
    senderWxid,
    senderRemark: contact?.remark ?? null,
    senderNickName: contact?.nickName ?? null,
    senderDisplayName: contact?.displayName ?? null,
    createTime: row.createTime,
    content: parsed ? parsed.body : row.content,
    rawHex: null,
  };
}
