import { Timeouts } from '@utility-lib/index';

export enum GrowthAmplitudeEvents {
  // referral events
  REFERRAL_PAGE_DISPLAY = 'referral page displayed',

  // delegate events
  OPEN_DELEGATE_HOME_SCREEN = 'open ea trips page',
  OPEN_HOW_IT_WORKS_DELEGATE = '"self signup continue on app opened"',

  // cashback events
  CASHBACK_PAGE_VIEW = 'cashback page view',

  // policy page events
  WATCH_VIDEO_CLICKED = 'admin policies page demo video opened'
}

export class AmplitudeEvents {
  static amplitudeEvents: string[] = [];
  static amplitudeEventsToTest: string[] = [];

  static interceptAmplitudeAPI(): void {
    this.amplitudeEvents = [];
    this.amplitudeEventsToTest = [];

    cy.intercept('POST', new RegExp('/2/httpapi'), ($req) => {
      const sentEventNames: string[] =
        $req.body.events?.map((event: any) => event.event_type) || [];
      this.amplitudeEvents.push(...sentEventNames);
    }).as('amplitudeBrowserSDK');

    cy.intercept('POST', 'https://api.amplitude.com/', ($req) => {
      const events: any[] = JSON.parse(
        decodeURIComponent($req.body).split('&')[2].split('=')[1]
      );
      const sentEventNames: string[] = events.map((event: any) => event.event_type);
      this.amplitudeEvents.push(...sentEventNames);
    }).as('amplitudeLegacySDK');
  }

  static addExpectedAmplitudeEvents(...eventNames: string[]): void {
    cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout);
    this.amplitudeEvents.push(...eventNames);
    this.amplitudeEventsToTest.push(...eventNames);
  }

  static expectAmplitudeEventsToBeSent(): void {
    cy.allure().logStep('Check amplitude events');
    cy.wait(Timeouts.SHORT_TIMEOUT_3_SEC.timeout).then(() =>
      cy
        .log(`Captured amplitude events: ${JSON.stringify(this.amplitudeEvents)}`)
        .log(
          `Captured amplitude events to test: ${JSON.stringify(
            this.amplitudeEventsToTest
          )}`
        )
        .then(() => {
          this.amplitudeEventsToTest.forEach((event: string) => {
            const eventIndex: number = this.amplitudeEvents.findIndex(
              (ampEvent) => event === ampEvent
            );
            expect(eventIndex, `Event '${event}' should have been sent`).to.be.gt(-1);
            this.amplitudeEvents.splice(0, eventIndex + 1);
          });
        })
    );
  }
}
