import { OAuth2Server } from 'oauth2-mock-server'
import proxy from 'koa-proxies'
// Using the core library here slows down loading time signoficantly
import getPort, { portNumbers } from 'get-port'
import { AuthProxy } from './AuthProxy.js'

/** @typedef {import('@web/dev-server-core').Plugin} Plugin */
/** @typedef {import('@web/dev-server-core').ServerStartParams} ServerStartParams */

const oauth2server = new OAuth2Server()
const authProxy = new AuthProxy()
let oauth2env

export default /** @type Plugin */ ({
  name: 'auth',

  /**
   * @param {ServerStartParams} args
   */
  async serverStart(args) {
    const port = await getPort({ port: portNumbers(8000, 8100) })
    const proxyPort = await getPort({ port: portNumbers(8000, 8100) })
    args.app.use(
      proxy('/auth', {
        target: `http://localhost:${port}`,
        // logs: true,
        rewrite: (path) => path.replace('/auth', ''),
      })
    )
    const jwtKey = await oauth2server.issuer.keys.generate('RS256')
    await oauth2server.start(port, 'localhost')
    await authProxy.start(proxyPort)

    oauth2env = {
      port,
      root: '/auth',
      jwtKey,
      issuer: oauth2server.issuer.url,
      tokenProxy: `http://localhost:${proxyPort}/proxy?u=`,
    }
  },

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

  serve(context) {
    if (context.path === '/demo/elements/authorization/env.js') {
      const data = {
        oauth2: oauth2env,
      }
      return `export default ${JSON.stringify(data)}`
    }
    return undefined
  },
})
