/**
 * Serve a html page to inject and test the library
 */
const express = require('express');
const webpack = require('webpack');
const webpackConfig = require('./webpack.config');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

webpackConfig.entry.app.unshift('webpack-hot-middleware/client?reload=true');

// no-dd-sa:javascript-express/missing-helmet
let app = express();
const compiler = webpack(webpackConfig);
const PORT = 9800;
const API_URL = process.env.API_URL || 'http://localhost:9000';

// webpack middleware to enable hot reloading without manual rebuilds
app.use(
  webpackDevMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath || '/',
  }),
);
app.use(webpackHotMiddleware(compiler));

const html = (apiKey, products, collections) => {
  const productString = products ? `data-products=${JSON.stringify(products)}` : '';
  const collectionString = collections ? `data-collections=${JSON.stringify(collections)}` : '';

  return `
  <html>
    <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <meta charset="UTF-8" />
      <title>Widget Debug</title>
    </head>
    <body>
      <div id="widget" ${productString} ${collectionString}></div>
      <script src="http://localhost:${PORT}/lib.js"></script>
      <script>
        let widget;
        
        const initWidget = async () => {
          widget = await AdalongWidget.initializeWidget({
            token: '${apiKey}',
            config: { 
              apiUrl: "${API_URL}",
              hideArrows: true 
            }
          });
          
          if (widget) {
            widget.load('#widget');
          }
        };

        initWidget();
      </script>
    </body>
  </html>
`;
};

app.get('/', (req, res) => {
  res.send(
    html(
      req.query.apiKey,
      req.query.products && req.query.products.split(','),
      req.query.collections && req.query.collections.split(','),
    ),
  );
});

app.get('/lib.js', (req, res) => {
  res.sendFile(`${process.cwd()}/dist/${webpackConfig.output.filename}`);
});

app.listen(PORT, () => console.log(`✅ Listening to port ${PORT}, 👉 http://localhost:${PORT}/`));
