import {
  getHubID,
  getHublet,
  useServerRenderContext,
} from '@hubspot/cms-components';
import {
  // @ts-expect-error -- types not flowing through properly
  fetchVideo,
  // @ts-expect-error -- types not flowing through properly
  HubSpotVideoParams,
  // @ts-expect-error -- types not flowing through properly
  VideoCrmObject,
} from '@hubspot/video-player-core';

type FetchHSVideoResult = VideoCrmObject | undefined;

export async function fetchHSVideoServerSide(
  videoType: 'hubspot_video' | 'embed',
  hubspotVideoParams?: HubSpotVideoParams
): Promise<FetchHSVideoResult> {
  if (videoType !== 'hubspot_video' || !hubspotVideoParams?.player_id) {
    return undefined;
  }

  const portalId = getHubID();
  const { environmentConfig } = useServerRenderContext();
  const env = environmentConfig.getInternalHSEnv();

  try {
    const response = await fetchVideo(
      hubspotVideoParams.player_id,
      portalId,
      env,
      getHublet()
    );
    return response.video;
  } catch (err) {
    console.error(err);
    return undefined;
  }
}
