import { IPopularPostsPeriod, IPostWithFavorites } from "#entities/posts";
import { apiFetch } from "../fetch";

interface IResult {
  info: {
    date: string;
    min_date: string;
    max_date: string;
    navigation_dates: Record<IPopularPostsPeriod, [string, string, string]>;
    range_desc: string;
    scale: IPopularPostsPeriod;
  };
  props: {
    currentPage: "popular_posts";
    today: string;
    earliest_date_for_popular: string;
    limit: number;
    count: number;
  };
  results: IPostWithFavorites[];
  base: {};
  result_previews: (
    | { type: "thumbnail"; server: string; name: string; path: string }
    | { type: "embed"; url: string; subject: string; description: string }
  )[];
  result_attachments: { server: string; name: string; path: string }[];
  result_is_image: boolean;
}

export async function fetchPopularPosts(
  date?: string,
  scale?: IPopularPostsPeriod,
  offset?: number
) {
  const path = `/posts/popular`;
  const params = new URLSearchParams();

  if (date) {
    params.set("date", date);
  }

  if (scale) {
    params.set("period", scale);
  }

  if (offset) {
    params.set("o", String(offset));
  }

  const result = await apiFetch<IResult>(path, { method: "GET" });

  return result;
}
