const { getPlatformStatus } = require("./platforms");

function createWebAuth(options = {}) {
  const platformStatus = options.getPlatformStatus || getPlatformStatus;

  function isConfigured() {
    const platforms = platformStatus().filter((platform) => platform.supported && platform.enabled);
    return platforms.length > 0 && platforms.some((platform) => platform.configured);
  }

  function isLocalhostLoginAvailable(req) {
    if (!req) return false;
    const host = normalizeHostName(req.hostname || req.get?.("host"));
    return host === "localhost" || host === "::1" || host === "::ffff:127.0.0.1" || host === "127.0.0.1" || host.startsWith("127.");
  }

  function getLocalhostLoginPlatform(req) {
    if (!isLocalhostLoginAvailable(req)) return null;
    return {
      id: "localhost",
      label: "Localhost Login",
      configured: true,
      enabled: true,
      supported: true,
      supportsLogin: true,
      loginPath: "/auth/localhost"
    };
  }

  function getPrimaryLoginPlatform(req) {
    const localhost = getLocalhostLoginPlatform(req);
    if (localhost) return localhost;
    const platforms = platformStatus().filter((platform) => platform.supported && platform.enabled && platform.supportsLogin);
    if (!platforms.length) return null;
    return platforms.find((platform) => platform.configured) || platforms[0];
  }

  function getLoginRedirectPath(req) {
    return getPrimaryLoginPlatform(req)?.loginPath || "/setup";
  }

  function requireConfigured(req, res, next) {
    if (!isConfigured() && !isLocalhostLoginAvailable(req) && !req.path.startsWith("/setup")) {
      return res.redirect("/setup");
    }
    return next();
  }

  function requireAuth(req, res, next) {
    if (!req.session?.user) return res.redirect(getLoginRedirectPath(req));
    return next();
  }

  return Object.freeze({
    isConfigured,
    isLocalhostLoginAvailable,
    getLocalhostLoginPlatform,
    getPrimaryLoginPlatform,
    getLoginRedirectPath,
    requireConfigured,
    requireAuth
  });
}

function normalizeHostName(value) {
  const raw = String(value || "").toLowerCase();
  if (raw.startsWith("[")) return raw.slice(1, raw.indexOf("]"));
  if (raw === "::1" || raw === "::ffff:127.0.0.1") return raw;
  return raw.replace(/:\d+$/, "");
}

module.exports = { createWebAuth, normalizeHostName };
