/// <reference types="cypress" />
describe('Two Factor', () => {
    const username = 'sysadmin';
    const userId = 66;
    beforeEach(() => {
        cy.visit('/#/login');
        cy.get('#switchLanguage').click();
        cy.get('.q-menu > :nth-child(1) > .q-item').click();
    });

    it('should enable two factor to sysadmin', () => {
        cy.request(
            'PATCH',
            `http://localhost:3000/api/VnUsers/${userId}/update-user?access_token=DEFAULT_TOKEN`,
            { twoFactor: 'email' }
        );
    });

    it('should fail when login with incorrect two factor', () => {
        cy.get('input[aria-label="Username"]').type(username);
        cy.get('input[aria-label="Password"]').type('nightmare');
        cy.get('button[type="submit"]').click();
        cy.get('.q-notification__message').should(
            'have.text',
            'Two-factor verification required'
        );

        cy.get('input[type="text"]').type('123456');
        cy.get('button[type="submit"]').click();
        cy.url().should('contain', '/twoFactor');
    });

    it('should login with correct two factor', () => {
        cy.get('input[aria-label="Username"]').type(username);
        cy.get('input[aria-label="Password"]').type('nightmare');
        cy.get('button[type="submit"]').click();
        cy.get('.q-notification__message').should(
            'have.text',
            'Two-factor verification required'
        );

        // Get code from mail
        cy.request(
            `http://localhost:3000/api/Mails?filter=%7B%22where%22%3A%20%7B%22receiver%22%3A%20%22${username}%40mydomain.com%22%7D%2C%20%22order%22%3A%20%5B%22id%20DESC%22%5D%7D&access_token=DEFAULT_TOKEN`
        ).then((response) => {
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = response.body[0].body;
            const codeElement = tempDiv.querySelector('.code');
            const code = codeElement ? codeElement.textContent.trim() : null;

            cy.get('input[type="text"]').type(code);
            cy.get('button[type="submit"]').click();
            cy.url().should('contain', '/dashboard');
        });
    });
});
