import { OAuth2Server } from 'oauth2-mock-server'
import getPort, { portNumbers } from 'get-port'

const oauth2server = new OAuth2Server()
let oauth2env

/** @typedef {import('@web/test-runner').TestRunnerConfig} TestRunnerConfig */

const filteredLogs = ['Running in dev mode', 'lit-html is in dev mode', 'Lit is in dev mode']

export default /** @type TestRunnerConfig */ ({
  nodeResolve: {
    browser: true,
  },
  files: ['.tmp/test/**/*.test.js', '.tmp/test/**/*.spec.js'],
  // files: ['.tmp/test/core/fragment_manager.spec.js'],

  concurrentBrowsers: 3,
  concurrency: 10,
  rootDir: './',

  /** Filter out lit dev mode logs */
  filterBrowserLogs(log) {
    for (const arg of log.args) {
      if (typeof arg === 'string' && filteredLogs.some((l) => arg.includes(l))) {
        return false
      }
    }
    return true
  },

  plugins: [
    {
      name: 'mock-api',
      serve(context) {
        if (context.path === '/.tmp/test/env.js') {
          const data = {
            oauth2: oauth2env,
          }
          return `export default ${JSON.stringify(data)}`
        }
        return undefined
      },
    },

    {
      name: 'servers',
      async serverStart() {
        const port = await getPort({ port: portNumbers(8000, 8100) })
        const jwtKey = await oauth2server.issuer.keys.generate('RS256')
        await oauth2server.start(port, 'localhost')
        oauth2env = {
          port,
          jwtKey,
          issuer: oauth2server.issuer.url,
        }
      },

      async serverStop() {
        await oauth2server.stop()
      },
    },
  ],

  testRunnerHtml: (testFramework) =>
    `<html class="theme-light">
    <head>
      <!-- m3 styles -->
      <link rel="stylesheet" href="/src/styles/m3/tokens.css" data-theme="tokens" />
      <link rel="stylesheet" href="/src/styles/m3/theme.css" data-theme="light" />
    </head>
    <body>
      <script type="module" src="${testFramework}"></script>
    </body>
  </html>`,

  testFramework: {
    config: {
      timeout: 60000,
    },
  },
  browserStartTimeout: 20000,
  testsStartTimeout: 20000,
  testsFinishTimeout: 30000,

  coverageConfig: {
    report: true,
    reporters: ['lcov', 'text'],
  },
})
