import { CmsResponse } from "@/types/TCms";
import React, { createContext, ReactNode, useContext } from "react";

interface CmsContextType {
  cmsData: CmsResponse | null;
}

const CmsContext = createContext<CmsContextType | undefined>(undefined);

interface CmsProviderProps {
  children: ReactNode;
  cmsData: CmsResponse | null;
}

export const CmsProvider: React.FC<CmsProviderProps> = ({
  children,
  cmsData,
}) => {
  return (
    <CmsContext.Provider value={{ cmsData }}>{children}</CmsContext.Provider>
  );
};

export const useCms = (): CmsContextType => {
  const context = useContext(CmsContext);
  if (context === undefined) {
    throw new Error("useCms must be used within a CmsProvider");
  }
  return context;
};

export async function fetchCmsData(
  id: string,
  cmsService: { getCms: (id: string) => Promise<CmsResponse> }
): Promise<CmsResponse | null> {
  try {
    const cmsData = await cmsService.getCms(id);
    return cmsData;
  } catch (error) {
    console.error("Error fetching CMS data:", error);
    return null;
  }
}
