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

export type AcademyExploreItem = {
  _id: string;
  courseId: string;
  type: "image" | "video";
  files?: { path?: string; type?: string }[];
  course_video?: string | null;
  course_images?: string[];
  course_image?: string;
  course_name?: string;
  teacher_name?: string;
  file_name?: string;
  caption?: string;
  user_id?: string;
  user_name?: string;
  first_name?: string;
  last_name?: string;
  profile_image?: string;
  likesCount?: number;
  createdAt?: string;
  status?: string;
};

type AcademyExploreResponse = {
  success?: boolean;
  data?: {
    items: AcademyExploreItem[];
    pagination?: {
      currentPage: number;
      totalPages: number;
      totalItems: number;
      hasNextPage: boolean;
    };
  };
};

export async function fetchAcademyExplore(
  page: number,
  limit: number,
  token: string
): Promise<{
  items: AcademyExploreItem[];
  hasNextPage: boolean;
}> {
  const apiUrl = `${getApiBaseUrl()}/academy/academy/explore/free-content?page=${page}&limit=${limit}`;

  const response = await fetch(apiUrl, {
    cache: "no-store",
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
    },
  });

  if (response.status === 404) {
    return { items: [], hasNextPage: false };
  }

  if (!response.ok) {
    throw new Error(`Academy explore failed: ${response.status}`);
  }

  const json = (await response.json()) as AcademyExploreResponse;
  const items = json.data?.items ?? [];
  const hasNextPage = json.data?.pagination?.hasNextPage ?? false;

  return { items, hasNextPage };
}
