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

const IntegrationsPageSelectors = {
  hrIntegrationCard: '.mat-card',
  hrIntegrationCardTitle: '[qaid="integrationBlockTitle"]',
  hrIntegrationCardDescription: '[qaid="integrationBlockDescription"]',
  hrIntegrationCardStartButton: '[qaid="setupInitialIntegration"]',
  newIntegrationGetStartedButton: '[text="Get started"]',
  mergeIFrame: '#merge-link-iframe'
};

export class IntegrationsPage {
  static visitIntegrationsPage() {
    cy.allure().logStep('Visit integrations page');
    cy.intercept('GET', /api\/hrms\/admin\/connections/).as('waitForIntegrations');
    cy.visit('app/admin2/company/integrations');
    cy.url().should('include', '/integrations');
    cy.wait('@waitForIntegrations');
  }

  static checkHrIntegrationBlockExist() {
    cy.allure().logStep('Check if hr integration page exists');
    cy.get(IntegrationsPageSelectors.hrIntegrationCard)
      .find(IntegrationsPageSelectors.hrIntegrationCardTitle)
      .contains('HR Integrations');
  }

  static checkHrIntegrationEmpty() {
    cy.allure().logStep('Check if hr integration is empty');
    cy.get(IntegrationsPageSelectors.hrIntegrationCard).find(
      IntegrationsPageSelectors.hrIntegrationCardDescription
    );
    cy.get(IntegrationsPageSelectors.hrIntegrationCard).find(
      IntegrationsPageSelectors.hrIntegrationCardStartButton
    );
  }

  static getIframeDocument = () => {
    return cy
      .get(IntegrationsPageSelectors.mergeIFrame)
      .its('0.contentDocument')
      .should('exist');
  };

  static getIframeBody = () => {
    return IntegrationsPage.getIframeDocument()
      .its(utilitySelector.bodySelector)
      .should('not.be.undefined')
      .then(cy.wrap);
  };

  static startHrIntegration() {
    cy.allure().logStep('Start hr integration');
    cy.intercept('POST', /api\/hrms\/admin\/merge\/link_token/).as('waitForLinkToken');
    cy.intercept('POST', /initiate/).as('waitForMergeInitiate');
    cy.intercept('PATCH', /linked-account/).as('waitForLinkedAccount');
    cy.intercept('POST', /api\/hrms\/admin\/merge\/public_token/).as(
      'waitForPublicToken'
    );
    cy.intercept('POST', 'api/integrations/linking-flow/next-page').as('waitForHris');
    cy.get(IntegrationsPageSelectors.hrIntegrationCard)
      .find(IntegrationsPageSelectors.hrIntegrationCardStartButton)
      .click();
    cy.get(IntegrationsPageSelectors.newIntegrationGetStartedButton).click();
    cy.wait('@waitForLinkToken');
    IntegrationsPage.getIframeBody();
  }
}
