// server.mjs

import * as https from 'https';
import url from 'url';
import fs from 'fs';
import path from 'path';
import open from 'open';

let subdomainName = process.argv[2] || 'www';
if (subdomainName) {
  subdomainName += '.';
}

const domainName = process.argv[3] || 'test.com';
const port = process.argv[4] || 443;

let options = {};

if (fs.existsSync(`./_wildcard.${domainName}.pem`)) {
  options = {
    key: fs.readFileSync(`./_wildcard.${domainName}-key.pem`),
    cert: fs.readFileSync(`./_wildcard.${domainName}.pem`),
  };
} else {
  console.log('Https enabled but no pem files found, exiting.');
  process.exit(1);
}

const server = https.createServer(options, (req, res) => {
  console.log(`${req.method} ${req.url}`);

  // parse URL
  const parsedUrl = new url.URL(req.url, `http://${req.headers.host}`);
  // extract URL path
  let pathname = `.${parsedUrl.pathname}`;
  // based on the URL path, extract the file extension. e.g., .js, .doc, ...
  let ext = path.parse(pathname).ext;
  ext = ext || '.html';

  // maps file extension to MIME type
  const map = {
    '.ico': 'image/x-icon',
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.json': 'application/json',
    '.css': 'text/css',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.wav': 'audio/wav',
    '.mp3': 'audio/mpeg',
    '.svg': 'image/svg+xml',
    '.pdf': 'application/pdf',
    '.doc': 'application/msword',
  };

  fs.promises
    .access(pathname)
    .then(() => fs.promises.readFile(pathname))
    .then((data) => {
      // if the file is found, set Content-type and send data
      res.setHeader('Content-type', map[ext] || 'text/plain');
      res.end(data);
    })
    .catch(() => {
      // if the file is not found, return 404
      res.statusCode = 404;
      res.end(`File ${pathname} not found!`);
    });
});

server.listen(parseInt(port));

const serveURL = `${'https'}://${subdomainName}${domainName}:${port}/index.html`;
console.log(`Server listening on ${serveURL}`);
open(serveURL);
