const fs = require("fs");
const path = require("path");

const REPO_ROOT = path.join(__dirname, "..", "..");

function handleRoot(req, res, host, reqPath) {
  // shell.peercortex.org → admin feedback terminal (check first)
  if (host === 'shell.peercortex.org') {
    try {
      const html = fs.readFileSync('/opt/peercortex-app/public/shell.html', 'utf8');
      res.setHeader('Content-Type', 'text/html; charset=utf-8');
      return res.end(html);
    } catch (_e) {
      res.writeHead(500);
      return res.end('shell.html not found');
    }
  }
  // v2.peercortex.org → redirect to main domain
  if (host === 'v2.peercortex.org') {
    res.writeHead(301, { Location: 'https://peercortex.org' + reqPath });
    return res.end();
  }
  const htmlFile = "index.html";
  try {
    const html = fs.readFileSync("/opt/peercortex-app/public/" + htmlFile, "utf8");
    res.setHeader("Content-Type", "text/html; charset=utf-8");
    return res.end(html);
  } catch (_e) {
    res.writeHead(500);
    return res.end(htmlFile + " not found");
  }
}

function handleIndexEditorial(req, res) {
  try {
    const html = fs.readFileSync("/opt/peercortex-app/public/index-editorial.html", "utf8");
    res.setHeader("Content-Type", "text/html; charset=utf-8");
    return res.end(html);
  } catch (_e) {
    res.writeHead(500);
    return res.end("index-editorial.html not found");
  }
}

function handleFavicon(req, res) {
  res.writeHead(204);
  return res.end();
}

function handleLia(req, res) {
  try {
    const liaHtml = fs.readFileSync(path.join(REPO_ROOT, "public", "lia.html"), "utf8");
    res.setHeader("Content-Type", "text/html; charset=utf-8");
    return res.end(liaHtml);
  } catch (_e) {
    res.writeHead(500);
    return res.end("lia.html not found");
  }
}

module.exports = { handleRoot, handleIndexEditorial, handleFavicon, handleLia };
