import { getMinimalMe } from '../../../support/helpers';
import { hasOperationName } from '../../../support/graphql';

const teacher = getMinimalMe();

const mockCreateTeamCall = (name) => {
  cy.intercept('POST', '/api/graphql', (req) => {
    if (hasOperationName(req, 'CreateTeamMutation')) {
      let result;
      if (name) {
        result = {
          __typename: 'TeamNode',
          id: 'newTeamId',
          name,
          code: 'ABC',
          members: [],
        };
      } else {
        result = {
          __typename: 'DuplicateName',
          reason: 'Dieser Name wird bereits verwendet.',
        };
      }
      req.reply({
        data: {
          createTeam: {
            result,
          },
        },
      });
    }
  });
};

describe('Team', () => {
  beforeEach(() => {
    cy.setup();
    cy.mockGraphqlOps({
      operations: {
        MeQuery: {
          me: {
            ...teacher,
            team: null,
          },
        },
      },
    });
  });

  it('creates a new team', () => {
    const name = 'Team Böhmi';

    mockCreateTeamCall(name);

    cy.visit('/me/team');

    cy.getByDataCy('create-team-button').click();
    cy.getByDataCy('join-form-input').type(name);
    cy.getByDataCy('join-form-confirm').click();

    cy.getByDataCy('group-list-name').should('contain', name);
  });

  it('tries to create team but fails due to duplicate name', () => {
    const name = "Gibt's schon";

    mockCreateTeamCall(false);
    cy.visit('/me/team');

    cy.getByDataCy('create-team-button').click();
    cy.getByDataCy('join-form-input').type(name);
    cy.getByDataCy('join-form-confirm').click();

    cy.getByDataCy('join-form-input-error').should('contain', 'Dieser Name wird bereits verwendet.');
  });
});
