import { Post } from "@/types/types";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import { resolvePostMediaType } from "@/lib/reelsMediaType";

const VIDEO_EXT = /\.(mp4|webm|mov|m4v|mkv)(\?|$)/i;

export function getVideoPoster(post: Post): string | undefined {
  if (post.post_image) return buildStorageUrl(post.post_image);
  const imageFile = post.files?.find((file) => file.type === "image");
  if (imageFile?.path) return buildStorageUrl(imageFile.path);
  const imagePath = post.post_images?.[0];
  if (imagePath) return buildStorageUrl(imagePath);
  return undefined;
}

export function getPostMedia(post: Post): {
  kind: "video" | "image";
  src: string;
  poster?: string;
} | null {
  const files = post.files || [];
  const firstFile = files[0];
  if (!firstFile?.path && !post.post_images?.length && !post.post_video) {
    return null;
  }

  const resolvedType = resolvePostMediaType(post);
  const videoFile = files.find((file) => file.type === "video");
  const isVideo =
    resolvedType === "video" ||
    Boolean(videoFile) ||
    (firstFile?.type === "video") ||
    (firstFile?.path ? VIDEO_EXT.test(firstFile.path) : false) ||
    Boolean(post.post_video);

  if (isVideo) {
    const videoPath = videoFile?.path || post.post_video || firstFile?.path;
    if (!videoPath) {
      const posterOnly = getVideoPoster(post);
      if (!posterOnly) return null;
      return { kind: "video", src: posterOnly, poster: posterOnly };
    }
    return {
      kind: "video",
      src: buildStorageUrl(videoPath),
      poster: getVideoPoster(post),
    };
  }

  const imagePath = firstFile?.path || post.post_images?.[0];
  if (!imagePath) return null;
  return { kind: "image", src: buildStorageUrl(imagePath) };
}
