import { getHublet, HSEnvironment } from '@hubspot/cms-components';
import { PageMeta } from '../types.js';

type TrackPlayParams = {
  crmObjectId: number;
  sessionId: string;
  contactUtk: string;
  pageMeta: PageMeta;
};

type RetentionParams = {
  secondsToViews: Record<string, number>;
  endState: boolean;
};

type CompletedPlayParams = {
  secondsViewed: number;
  percentageViewed: number;
};

const getApiDomain = (env?: HSEnvironment) => {
  const computedEnv = env || 'prod';
  return computedEnv === 'qa' ? 'hubspotqa.com' : 'hubspot.com';
};

const getApiOrigin = (env?: HSEnvironment) => {
  const hublet = getHublet();
  const apiSubdomainWithHublet = hublet === 'na1' ? 'api' : `api-${hublet}`;
  return `https://${apiSubdomainWithHublet}.${getApiDomain(env)}`;
};

export const trackPlayEvent = async (
  env: HSEnvironment,
  portalId: number,
  params: TrackPlayParams
) => {
  const data = {
    ...params.pageMeta,
    crmObjectId: params.crmObjectId,
    sessionId: params.sessionId,
    contactUtk: params.contactUtk,
  };

  const response = await fetch(
    `${getApiOrigin(
      env
    )}/media-bridge/public/v1/media/played?portalId=${portalId}`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    }
  );

  if (!response.ok) {
    const errorData = {
      status: response.status,
      requestBody: data,
      responseText: await response.text(),
    };

    console.error('Failed to track play event', {
      extra: errorData,
      level: 'warning',
      tags: { status: response.status },
    });
  }
};

export const trackSecondsViewed = async (
  env: HSEnvironment,
  portalId: number,
  params: TrackPlayParams,
  retentionParams: RetentionParams
) => {
  let query = `portalId=${portalId}`;
  if (retentionParams.endState) {
    query += `&endState=true`;
  }

  const data = {
    ...params.pageMeta,
    crmObjectId: params.crmObjectId,
    sessionId: params.sessionId,
    contactUtk: params.contactUtk,
    secondsToViews: retentionParams.secondsToViews,
  };

  const response = await fetch(
    `${getApiOrigin(env)}/media-bridge/public/v1/media/seconds-viewed?${query}`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    }
  );

  if (!response.ok) {
    const errorData = {
      status: response.status,
      requestBody: data,
      responseText: await response.text(),
    };

    console.error('Failed to track seconds viewed', {
      extra: errorData,
      level: 'warning',
      tags: { status: response.status },
    });
  }
};

export const trackCompletedPlay = async (
  env: HSEnvironment,
  portalId: number,
  params: TrackPlayParams,
  completedPlayParams: CompletedPlayParams
) => {
  if (!window.navigator || typeof window.navigator.sendBeacon !== 'function') {
    return false;
  }

  try {
    const data = new Blob(
      [
        JSON.stringify({
          crmObjectId: params.crmObjectId,
          sessionId: params.sessionId,
          contactUtk: params.contactUtk,
          ...params.pageMeta,
          ...completedPlayParams,
        }),
      ],
      { type: 'text/plain' }
    );
    return window.navigator.sendBeacon(
      `${getApiOrigin(
        env
      )}/media-bridge/public/v1/media/completed-play?portalId=${portalId}`,
      data
    );
  } catch (err) {
    console.error('Error tracking final attention span', err);
    return false;
  }
};
