const DEFAULT_ROOT_DOMAIN = process.env.PLATFORM_ROOT_DOMAIN || 'platform.com';
const DEFAULT_ADMIN_SUBDOMAIN = process.env.ADMIN_SUBDOMAIN || 'admin';
const DEFAULT_STAGE_SUBDOMAIN = process.env.STAGE_SUBDOMAIN || 'stage';

function stripPort(hostname = '') {
  return hostname.split(':')[0].toLowerCase();
}

function getRequestHost(req) {
  const forwardedHost = req.headers['x-forwarded-host'];
  const hostHeader = Array.isArray(forwardedHost) ? forwardedHost[0] : forwardedHost || req.headers.host;
  return stripPort(hostHeader || '');
}

function detectRuntimeContext(hostname) {
  const host = stripPort(hostname);

  if (!host) {
    return {
      mode: 'unknown',
      projectSlug: null,
      host,
      rootDomain: DEFAULT_ROOT_DOMAIN,
    };
  }

  if (host === 'localhost' || host === '127.0.0.1') {
    return {
      mode: 'admin',
      projectSlug: null,
      host,
      rootDomain: DEFAULT_ROOT_DOMAIN,
    };
  }

  const rootParts = DEFAULT_ROOT_DOMAIN.split('.').filter(Boolean);
  const hostParts = host.split('.').filter(Boolean);

  if (hostParts.length > rootParts.length) {
    const suffix = hostParts.slice(-rootParts.length).join('.');

    if (suffix === DEFAULT_ROOT_DOMAIN) {
      const prefixParts = hostParts.slice(0, -rootParts.length);

      if (prefixParts.length === 1 && prefixParts[0] === DEFAULT_ADMIN_SUBDOMAIN) {
        return {
          mode: 'admin',
          projectSlug: null,
          host,
          rootDomain: DEFAULT_ROOT_DOMAIN,
        };
      }

      if (
        prefixParts.length === 2 &&
        prefixParts[0] === DEFAULT_STAGE_SUBDOMAIN &&
        prefixParts[1] !== DEFAULT_ADMIN_SUBDOMAIN
      ) {
        return {
          mode: 'stage',
          projectSlug: prefixParts[1],
          host,
          rootDomain: DEFAULT_ROOT_DOMAIN,
        };
      }

      if (
        prefixParts.length === 1 &&
        ![DEFAULT_ADMIN_SUBDOMAIN, DEFAULT_STAGE_SUBDOMAIN].includes(prefixParts[0])
      ) {
        return {
          mode: 'production',
          projectSlug: prefixParts[0],
          host,
          rootDomain: DEFAULT_ROOT_DOMAIN,
        };
      }
    }
  }

  return {
    mode: 'unknown',
    projectSlug: null,
    host,
    rootDomain: DEFAULT_ROOT_DOMAIN,
  };
}

function runtimeContextMiddleware(req, res, next) {
  const host = getRequestHost(req);
  const context = detectRuntimeContext(host);

  req.runtimeContext = context;

  res.setHeader('x-runtime-mode', context.mode);
  if (context.projectSlug) {
    res.setHeader('x-runtime-project', context.projectSlug);
  }

  next();
}

module.exports = {
  runtimeContextMiddleware,
  detectRuntimeContext,
};
