const API = Cypress.env('API');

const headers = {
    Authorization: '',
};

Cypress.Commands.add('loginUser', () => {
    return cy.readFile('aad-tokens.json')
        .then(creds => {
            // set auth headers so test setup calls are authorized
            headers.Authorization = `Bearer ${creds['msal.idtoken']}`;

            // put MS Azure AD creds in session storage
            // so application under test will be logged in.
            for (let key in creds) {
                if (
                    key.startsWith('msal.') ||
                    key.startsWith('{"authority":')
                ) {
                    sessionStorage[key] = creds[key];
                }
            }
      });
});

// example of custom command using headers configured via loginUser
Cypress.Commands.add('APICreate', (url, instance) => {
    Cypress.log({
        name: 'APICreate',
        message: url + ' | ' + JSON.stringify(instance)
    })
    return cy.request({
        method: 'POST',
        headers: headers,
        url: `${API}/${url}`,
        body: instance
    }).then(data => data.body);
});