import { FeedItem, getAvatarUrl, getFeedImageUrl, getVideoUrl, getAudioUrl, isOwnFeed, type TeamMember } from "../services/feedService";

export interface PostCardModel {
  id: string;
  authorName: string;
  authorUsername: string;
  authorAvatar: string;
  image: string;
  title: string;
  caption: string;
  likes: number;
  dislikes: number;
  comments: number;
  timestamp: string;
  topicName: string;
  initialComments: any[];
  mediaType: "image" | "video" | "audio";
  mediaUrl?: string;
  isOwnPost: boolean;
  initialLikeState: "پسند" | "عدم پسند" | "";
  missionType: string;
  workflowID: string;
  teamMemberIds?: string;
  preloadedTeamMembers?: TeamMember[];
}

const isNonEmptyString = (value: any): value is string => {
  return typeof value === "string" && value.trim().length > 0;
};

export const mapFeedItemToPostCardModel = (
  item: FeedItem,
  topicServerName: string
): PostCardModel => {
  const hasImage = isNonEmptyString(item.image);
  const hasVideo = isNonEmptyString(item.film);
  const hasAudio = isNonEmptyString(item.audio);

  let mediaType: "image" | "video" | "audio" = "image";
  let mediaUrl: string | undefined = undefined;
  let coverImage = "";

  if (hasVideo) {
    mediaType = "video";
    mediaUrl = getVideoUrl(item.StageID);
    coverImage = hasImage ? getFeedImageUrl(item.StageID) : "";
  } else if (hasAudio) {
    mediaType = "audio";
    mediaUrl = getAudioUrl(item.StageID);
    coverImage = hasImage ? getFeedImageUrl(item.StageID) : "";
  } else if (hasImage) {
    mediaType = "image";
    coverImage = getFeedImageUrl(item.StageID);
  }

  const postTimestamp =
    item.datetimee || item.datetime1 || item.create_date || "";

  return {
    id: item.StageID.toString(),
    authorName: item.full_name,
    authorUsername: item.full_name,
    authorAvatar: getAvatarUrl(item.person_stage_id),
    image: coverImage,
    title: item.title,
    caption: item.description,
    likes: item.like_count,
    dislikes: item.dislike_count,
    comments: item.comment_count,
    timestamp: postTimestamp,
    topicName: topicServerName,
    initialComments: [],
    mediaType,
    mediaUrl,
    isOwnPost: isOwnFeed(item.user_id),
    initialLikeState: item.like_state as "پسند" | "عدم پسند" | "",
    missionType: topicServerName,
    workflowID: item.workflow_ID || item.StageID.toString(),
    teamMemberIds: item.team_member,
  };
};
