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

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

  const tryUrls = [
    `${BASE_URL}/posts/${id}`,
    `${BASE_URL}/posts/web/${id}`,
    `${BASE_URL}/posts/get/${id}`,
  ];

  for (const url of tryUrls) {
    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 */
    }
  }

  try {
    const res = await fetch(
      `${BASE_URL}/users/web?page=1&limit=50&_id=${id}`,
      { cache: "no-store", headers }
    );
    if (res.ok) {
      const data = await res.json();
      const found = (data?.posts as Post[])?.find((p) => p._id === id);
      if (found) return found;
    }
  } catch {
    /* ignore */
  }

  return null;
}
