import { getApiBaseUrl } from "@/components/main/BaseUrl";
import { Post } from "@/types/types";

/** Fetch a single post by id */
export async function fetchPostById(
  id: string,
  token?: string
): Promise<Post | null> {
  const base = getApiBaseUrl();
  const headers: HeadersInit = token
    ? { Authorization: `Bearer ${token}` }
    : {};

  const primaryUrl = `${base}/posts/web/${id}`;

  try {
    const res = await fetch(primaryUrl, {
      cache: "no-store",
      headers,
    });
    if (res.ok) {
      const data = await res.json();
      const post = data?.post ?? data?.data ?? data;
      if (post?._id) return post as Post;
    }
  } catch {
    /* try fallbacks */
  }

  const fallbackUrls = [
    `${base}/posts/${id}`,
    `${base}/posts/get/${id}`,
  ];

  for (const url of fallbackUrls) {
    try {
      const res = await fetch(url, {
        cache: "no-store",
        headers,
      });
      if (!res.ok) continue;
      const data = await res.json();
      const post = data?.post ?? data?.data ?? data;
      if (post?._id) return post as Post;
    } catch {
      /* try next */
    }
  }

  return null;
}
