/**
 * atk_caching.cy.js
 *
 * Caching tests.
 *
 */

/** ESLint directives */
/* eslint-disable import/first */

/// <reference types='Cypress' />

// Set up ATK.
import * as atkCommands from '../../support/atk_commands' // eslint-disable-line no-unused-vars
import * as atkUtilities from '../../support/atk_utilities'
import atkConfig from '../../../cypress.atk.config'

// Standard accounts that use user accounts created
// by QA Accounts. QA Accounts are created when the QA
// Accounts module is enabled.
import qaUserAccounts from '../../data/qaUsers.json'

describe('Caching tests.', () => {
  const ctx = { tmpNid: [] }

  //
  // Validate Caching.
  //
  it('(ATK-CY-1090) Verify block caching and cache tag functionality.', { tags: ['@ATK-CY-1090', '@caching', '@smoke', '@alters-db'] }, () => {
    const testId = 'ATK-CY-1090'
    const state1 = atkUtilities.createRandomString(10)
    const state2 = atkUtilities.createRandomString(10)

    // Log in as admin.
    cy.logInViaForm(qaUserAccounts.admin)

    // Create a page.
    cy.visit(atkConfig.pageAddUrl)
    cy.get('input[name="title[0][value]"]').type(`${testId}: A Title`)
    cy.inputCKEditor(`A page to test ${testId}`)
    cy.save()
    cy.url().then((url) => {
      // Extract the nid placed in the body class by this hook:
      // automated_testing_kit.module:automated_testing_kit_preprocess_html().
      cy.getNid().then((nid) => {
        ctx.tmpNid.push(nid)
      })

      // Create a custom block.
      cy.visit(atkConfig.blockAddUrl)
      cy.get('[name="info[0][value]"]').type(`${testId}: Custom block`)
      cy.inputCKEditor(`Block content state ${state1}`)
      cy.save()

      // Place the newly created block, restricted by the newly created page.
      cy.visit('admin/structure/block')
      cy.get('.region-title-content').contains('Place block').click()
      cy.contains('tr', testId).contains('Place block').click()
      cy.contains('#drupal-modal li', 'Pages').click()
      cy.get('textarea').type(new URL(url).pathname)
      cy.contains('button:visible', 'Save block').click()

      // Log out.
      // Load the main page with Cypress.
      // Confirm header X-Drupal-Cache: MISS
      cy.intercept(url).as('page')
      cy.logOutViaUi()
      cy.visit(url)

      cy.wait('@page').then((response) => {
        const cache = response.response.headers['x-drupal-cache']
        expect(cache).eq('MISS')
      })

      // Load the main page again.
      cy.visit(url)
      cy.wait('@page').then((response) => {
        const cache = response.response.headers['x-drupal-cache']
        expect(cache).eq('HIT')
      })

      // Edit the block content.
      cy.logInViaForm(qaUserAccounts.admin)
      cy.visit('admin/structure/block')
      cy.contains('tr', testId).contains('a', 'Edit block')
        .invoke('attr', 'href').then((editBlockUrl) => {
          cy.visit(editBlockUrl)
          cy.inputCKEditor(`Block content state ${state2}`)
          cy.save()
        })

      // Log out.
      // Load the main page with Cypress.
      // Confirm header X-Drupal-Cache: MISS
      cy.intercept(url).as('page')
      cy.logOutViaUi()
      cy.visit(url)

      cy.wait('@page').then((response) => {
        const cache = response.response.headers['x-drupal-cache']
        expect(cache).eq('MISS')
      })

      // Load the main page again.
      cy.visit(url)
      cy.wait('@page').then((response) => {
        const cache = response.response.headers['x-drupal-cache']
        expect(cache).eq('HIT')
      })
    })
  })

  after(() => {
    // Delete the page.
    ctx.tmpNid.forEach((nid) => {
      cy.deleteNodeWithNid(nid)
    })

    // Remove the block from the content layout.
    cy.logInViaForm(qaUserAccounts.admin)
    cy.visit('admin/structure/block')
    cy.get('a[aria-label^="Delete ATK-"]').each(($a) => {
      const deleteBlockUrl = $a.attr('href')
      cy.visit(deleteBlockUrl)
      cy.get('#edit-submit').click({ force: true })
    })

    // Delete the block.
    cy.visit('admin/content/block')
    cy.get('a[aria-label^="Delete ATK-"]').each(($a) => {
      const deleteBlockUrl = $a.attr('href')
      cy.visit(deleteBlockUrl)
      cy.get('#edit-submit').click({ force: true })
    })
  })
})
