import Api from './services/api';
import { AnalyticsConsent } from './services/analyticsConsent';
import { trackOrder, TrackOrderPayload, TrackOrderItemInput } from './integrations/tracking/order';

export interface TrackConfiguration {
  apiUrl?: string;
  hasAnalyticsConsent?: boolean;
}

const configure = (config: TrackConfiguration = {}): void => {
  if (config.apiUrl) {
    Api.initialize({ debug: { apiUrl: config.apiUrl } });
  }

  if (typeof config.hasAnalyticsConsent === 'boolean') {
    AnalyticsConsent.set(config.hasAnalyticsConsent);
  }
};

const setHasAnalyticsConsent = (granted: boolean): void => {
  AnalyticsConsent.set(Boolean(granted));
};

const AdalongTrack = {
  trackOrder,
  configure,
  setHasAnalyticsConsent,
};

type AdalongTrackAPI = typeof AdalongTrack;

declare global {
  interface Window {
    AdalongTrack: AdalongTrackAPI;
  }
}

if (typeof window !== 'undefined') {
  window.AdalongTrack = AdalongTrack;
}

export { trackOrder, configure, setHasAnalyticsConsent };
export type { TrackOrderPayload, TrackOrderItemInput };
export default AdalongTrack;
