/**
 * atk_cors.spec.js
 *
 * FedRAMP CORS security tests.
 */

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

// Set up Playwright.
import { expect, test } from '@playwright/test'

// eslint-disable-next-line no-unused-vars
import * as atkCommands from '../support/atk_commands'
// eslint-disable-next-line no-unused-vars
import * as atkUtilities from '../support/atk_utilities'

import playwrightConfig from '../../playwright.config'

// eslint-disable-next-line no-unused-vars
const baseUrl = playwrightConfig.use.baseURL

// Import ATK Configuration.
// eslint-disable-next-line no-unused-vars
import atkConfig from '../../playwright.atk.config'

// Standard accounts that use user accounts created
// by QA Accounts. QA Accounts are created when the QA
// Accounts module is enabled.
// eslint-disable-next-line no-unused-vars
import qaUserAccounts from '../data/qaUsers.json'

// // ***ALTERNATIVE: actually bypass cross-origin and analyze headers.***
// test.use({
//   bypassCSP: true,
//   launchOptions: {
//     args: ['--disable-web-security'],
//   },
// })

test.describe('Fed RAMP CORS security test', () => {
  //
  // Test attempts to get cross-origin content from a Drupal page.
  //
  test('(ATK-PW-1210) Basic CORS enforcement (deny unauthorized origin) @ATK-PW-1210 @fedramp @cors', async ({ page }) => {
    await page.goto('https://google.com')

    const statusCode = await page.evaluate((url) => fetch(url)
      .then((response) => response.status)
      .catch(() => 403), [baseUrl])
    expect(statusCode).toEqual(403)
  })

  //
  // This test simulates a preflight for a POST to a Drupal form route
  // (e.g., login) and checks for absence or restrictiveness of CORS headers,
  // ensuring the server does not permit unauthorized flows.
  //
  test('(ATK-PW-1211) Preflight CORS  @ATK-PW-1211 @fedramp @cors', async ({ page }) => {
    await page.goto('https://google.com')

    const loginUrl = `${baseUrl}${atkConfig.logInUrl}`

    // eslint-disable-next-line no-unused-vars
    let preflightHeaders
    page.on('response', (response) => {
      if (response.request().url() === loginUrl) {
        preflightHeaders = response.headers()
      }
    })

    const statusCode = await page.evaluate((url) => fetch(url, {
      method: 'OPTIONS',
      headers: {
        'Access-Control-Request-Method': 'POST',
      },
    }).then((response) => response.status).catch(() => 403), [loginUrl])

    expect(statusCode).toEqual(403)

    // // Blocked responses are not available.
    // expect(preflightHeaders).toBeDefined()
    // expect(preflightHeaders).not.toHaveProperty('access-control-allow-origin')
  })
})
