import { GraphQLError } from 'graphql';
import {assertStartPage} from '../../../support/helpers';

const schema = require('../../../fixtures/schema.json');

const redeemCoupon = coupon => {
  if (coupon !== '') {
    cy.get('[data-cy="coupon-input"]').type(coupon);
  }
  cy.get('[data-cy="coupon-button"]').click();
};

describe('Email Verification', () => {
  beforeEach(() => {
    cy.server();
  });

  it('forwards to homepage if confirmation key is correct', () => {
    cy.viewport('macbook-15');
    cy.mockGraphql({
      schema: schema,
      operations: {
        Coupon: {
          coupon: {
            success: true
          }
        },
      }
    });
    cy.apolloLogin('rachel.green', 'test');

    cy.visit('/license-activation');
    redeemCoupon('12345asfd');
    assertStartPage();
  });

  it('displays error if input is missing', () => {
    cy.viewport('macbook-15');
    cy.apolloLogin('rachel.green', 'test');

    cy.visit('/license-activation');
    redeemCoupon('');
    cy.get('[data-cy="coupon-local-errors"]').contains('Coupon ist ein Pflichtfeld');
  });

  it('displays error if coupon input is wrong', () => {
    cy.viewport('macbook-15');
    cy.mockGraphql({
      schema: schema,
      operations: {
        Coupon: new GraphQLError('invalid_coupon')
      }
    });
    cy.apolloLogin('rachel.green', 'test');

    cy.visit('/license-activation');
    redeemCoupon('12345asfd');
    cy.get('[data-cy="coupon-remote-errors"]').contains('Der angegebene Coupon-Code ist ungültig.');
  });

  it('displays error if an error occures', () => {
    cy.viewport('macbook-15');
    cy.mockGraphql({
      schema: schema,
      operations: {
        Coupon: new GraphQLError('unknown_error')
      }
    });
    cy.apolloLogin('rachel.green', 'test');

    cy.visit('/license-activation');
    redeemCoupon('12345asfd');
    cy.get('[data-cy="coupon-remote-errors"]').contains('Es ist ein Fehler aufgetreten. Bitte versuchen Sie es nochmals oder kontaktieren Sie den Administrator.');
  });
});
