import moment from "moment";
import { IBlogComment } from "@/api/types/blog";

export const AVATAR_FALLBACK = "/assets/images/avatar-dummy.png";

export interface MappedBlogComment {
  id: number;
  authorUserId: number;
  author: string;
  rank?: string;
  avatar: string;
  parentId?: number;
  date: string;
  content: string;
  likes: number;
  replies?: MappedBlogComment[];
  repliesCount: number;
}

export const mapBlogComment = (comment: IBlogComment): MappedBlogComment => {
  // `replies` is a paginated block ({ data, totalRecords, ... }); older payloads
  // may still send a flat array, so handle both shapes defensively.
  const repliesBlock = comment.replies as
    | IBlogComment["replies"]
    | IBlogComment[]
    | undefined;
  const replyData = Array.isArray(repliesBlock)
    ? repliesBlock
    : (repliesBlock?.data ?? []);
  const repliesCount = Array.isArray(repliesBlock)
    ? repliesBlock.length
    : (repliesBlock?.totalRecords ?? replyData.length);

  return {
    id: comment.id,
    authorUserId: comment.author?.id,
    author: comment.author?.name ?? "Anonymous",
    rank: comment.author?.rank,
    avatar: comment.author?.profileImage?.filePath ?? AVATAR_FALLBACK,
    date: moment(comment.createdAt).format("MMMM D, YYYY"),
    content: comment.content,
    likes: 0,
    replies: replyData.map(mapBlogComment),
    repliesCount,
    parentId: comment.parentId ?? undefined,
  };
};
