import { Post } from "@/types/types";

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

export type ReelsMediaType = "image" | "video";

type PostMediaSource = Pick<Post, "type" | "files"> | null | undefined;

export function resolvePostMediaType(
  post: PostMediaSource
): ReelsMediaType | undefined {
  if (post?.type === "video" || post?.type === "image") return post.type;
  const file = post?.files?.[0];
  const fileType = file?.type;
  if (fileType === "video" || fileType === "image") return fileType;
  if (file?.path && VIDEO_EXT.test(file.path)) return "video";
  return undefined;
}

export function resolveReelsMediaType(
  post: PostMediaSource,
  videoOnly = false
): ReelsMediaType | undefined {
  if (videoOnly) return "video";
  return resolvePostMediaType(post);
}

export function postMatchesReelsMediaType(
  post: Pick<Post, "type" | "files">,
  mediaType?: ReelsMediaType
): boolean {
  if (!mediaType) return true;
  const resolved = resolvePostMediaType(post);
  return !resolved || resolved === mediaType;
}
