import type { Category, Resource } from "../api";
import type { Attachment, Post } from "../types/post";
import {
  postDisplayText,
  postTitleText,
} from "../components/messageStream/utils/postText";

export type PostBackedResource = Resource & {
  downloadPostId?: string;
  downloadAttachmentId?: string;
};

function inferType(post: Post, att: Attachment | undefined): string {
  if (post.postType) return post.postType;
  if (!att) return post.text?.includes("http") ? "link" : "text";
  if (att.kind === "video") return "video";
  if (att.kind === "image") return "image";
  const ext = att.filename.split(".").pop()?.toLowerCase() ?? "";
  if (["ppt", "pptx", "key"].includes(ext) || att.mime.includes("presentation"))
    return "ppt";
  if (ext === "pdf" || att.mime === "application/pdf") return "pdf";
  if (att.mime.startsWith("audio/") || ext === "mp3") return "music";
  if (["zip", "rar", "7z", "tar", "gz"].includes(ext)) return "archive";
  return "text";
}

function coverFor(att: Attachment | undefined) {
  if (!att) return "";
  if (att.kind === "image" || att.mime.startsWith("image/")) {
    return att.thumbnailUrl || att.url;
  }
  return att.posterUrl || att.thumbUrl || att.thumbnailUrl || "";
}

export function postToResource(
  post: Post,
  lang: string,
  categories: Category[] = [],
): PostBackedResource {
  const first = post.attachments[0];
  const title = postTitleText(post, lang) || first?.filename || post.id;
  const category = categories.find((c) => c.id === post.categoryId);
  return {
    id: post.id,
    title,
    description: postDisplayText(post, lang),
    type: inferType(post, first),
    language: post.language,
    categoryId: post.categoryId,
    categorySlug: post.categorySlug,
    categoryName: category?.name || post.categorySlug,
    coverImage: coverFor(first),
    fileUrl: first?.url,
    previewUrl: first?.posterUrl || first?.thumbnailUrl,
    externalUrl: undefined,
    bodyText: postDisplayText(post, lang),
    badgeLabel: post.isRecommended ? "Recommended" : undefined,
    isDownloadable: !!first,
    isRecommended: post.isRecommended,
    publishedAt: post.publishedAt,
    updatedAt: post.updatedAt || post.publishedAt,
    tags: post.tags,
    downloadPostId: post.id,
    downloadAttachmentId: first?.id,
  };
}
