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

    it('should go to recover password section and send notification', () => {
        cy.get('input[aria-label="Username"]').type(username);
        cy.get(`a[href="#/recoverPassword?user=${username}"]`).click();

        cy.waitForElement('input[aria-label="User or recovery email"]');
        cy.get('input[aria-label="User or recovery email"]').should(
            'have.value',
            username
        );

        cy.get('button[type="submit"]').click();
        cy.get('.q-notification__message').should('have.text', 'Notification sent');
    });

    it('should change password to user', () => {
        // Get token 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 regex = /access_token=([a-zA-Z0-9]+)/;
            const [match] = response.body[0].body.match(regex);

            const resetUrl = '/#/resetPassword?' + match;
            cy.visit(resetUrl);
        });

        // Change password
        const newPassword = 'test.1234';
        cy.waitForElement('input[aria-label="Password"]');
        cy.waitForElement('input[aria-label="Repeat password"]');
        cy.get('input[aria-label="Password"]').type(newPassword);
        cy.get('input[aria-label="Repeat password"]').type(newPassword);

        cy.get('button[type="submit"]').click();
        cy.get('.q-notification__message').should('have.text', 'Password changed');

        // Try to login successfully
        cy.get('input[aria-label="Username"]').type(username);
        cy.get('input[aria-label="Password"]').type(newPassword);
        cy.get('button[type="submit"]').click();
        cy.url().should('contain', '/dashboard');

        // ❗The password cannot be returned because "nightmare" does not meet the requirements
    });
});
