/*
 * Copyright (c) 2023 AccelByte Inc. All Rights Reserved
 * This is licensed software from AccelByte Inc, for limitations
 * and restrictions contact your company contract manager.
 */

import fs from 'node:fs'
import express from 'express'

/* eslint-disable */
require('dotenv').config({ path: 'storybook/.env' })

export async function createServer(root = process.cwd(), _isProd = process.env.NODE_ENV === 'production', hmrPort: number) {
  const app = express()

  const vite = await (
    await import('vite')
  ).createServer({
    root,
    logLevel: 'error',
    server: {
      middlewareMode: true,
      watch: {
        // During tests we edit the files too fast and sometimes chokidar
        // misses change events, so enforce polling for consistency
        usePolling: true,
        interval: 100
      },
      hmr: {
        port: hmrPort
      },
      proxy: {
        '/favicon.ico': 'https://development.accelbyte.io/favicon.ico',

        '/api/cdn-bucket': {
          target: 'https://cdn.development.accelbyte.io/public/',
          changeOrigin: true,
          rewrite: path => {
            return path.replace(/^\/api\/cdn-bucket/, '')
          }
        },

        '/api': {
          target: process.env.JUSTICE_BASE_URL || 'https://development.accelbyte.io',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, ''),
          configure: proxy => {
            proxy.on('proxyRes', proxyRes => {
              proxyRes.headers['x-ab-www-authenticate'] = proxyRes.headers['www-authenticate']
              delete proxyRes.headers['www-authenticate']
            })
          }
        }
      }
    },
    appType: 'custom'
  })
  // use vite's connect instance as middleware
  app.use(vite.middlewares)

  app.use('*', async (req, res) => {
    try {
      const url = req.originalUrl

      // always read fresh template in dev
      let template: string = fs.readFileSync('playground/index.html', 'utf-8')
      template = await vite.transformIndexHtml(url, template)
      const renderHtml = (await vite.ssrLoadModule('playground/entry-server.tsx'))?.renderHtml

      const styleString = (await vite.ssrLoadModule('playground/App.tsx'))?.styleString

      const appHtml = await renderHtml(req)

      const html = template
        .replace(`<!--app-html-->`, appHtml)
        .replace(`/* style */`, styleString)
        .replace(
          '/* env script */',
          `window.process = ${JSON.stringify({
            env: process.env
          })}`
        )

      res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
    } catch (e: any) {
      vite?.ssrFixStacktrace(e)
      console.log(e.stack)
      res.status(500).end(e.stack)
    }
  })

  return { app, vite }
}

// @ts-ignore
createServer().then(({ app }) =>
  app.listen(5173, () => {
    console.log('http://localhost:5173')
  })
)
