const cors = require("cors");

const DEFAULT_PRODUCTION_ORIGINS = ["https://smartposapp.vercel.app"];

function normalizeOrigin(value) {
  if (!value) return null;
  const trimmed = String(value).trim();
  if (!trimmed) return null;
  return trimmed.replace(/\/$/, "");
}

function collectAllowedOrigins() {
  const origins = new Set();

  const frontend = normalizeOrigin(process.env.FRONTEND_URL);
  if (frontend) origins.add(frontend);

  const corsOrigin = process.env.CORS_ORIGIN;
  if (corsOrigin) {
    for (const part of corsOrigin.split(",")) {
      const origin = normalizeOrigin(part);
      if (origin) origins.add(origin);
    }
  }

  if (process.env.VERCEL || process.env.NODE_ENV === "production") {
    for (const origin of DEFAULT_PRODUCTION_ORIGINS) {
      origins.add(origin);
    }
  }

  if (process.env.NODE_ENV !== "production") {
    origins.add("http://localhost:5173");
    origins.add("http://localhost:3000");
    origins.add("http://127.0.0.1:5173");
  }

  return origins;
}

function isOriginAllowed(origin, allowedOrigins) {
  if (!origin) return true;
  const normalized = normalizeOrigin(origin);
  if (allowedOrigins.size === 0) return true;
  return Boolean(normalized && allowedOrigins.has(normalized));
}

function applyCorsHeaders(req, res, allowedOrigins) {
  const origin = req.headers.origin;
  if (origin && isOriginAllowed(origin, allowedOrigins)) {
    res.setHeader("Access-Control-Allow-Origin", origin);
    res.setHeader("Vary", "Origin");
  }
  res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
}

function createCorsMiddleware() {
  const allowedOrigins = collectAllowedOrigins();

  const options = {
    methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allowedHeaders: ["Content-Type", "Authorization"],
    credentials: false,
    origin(origin, callback) {
      if (isOriginAllowed(origin, allowedOrigins)) return callback(null, true);
      return callback(null, false);
    },
  };

  const corsMiddleware = cors(options);

  return function corsHandler(req, res, next) {
    applyCorsHeaders(req, res, allowedOrigins);
    if (req.method === "OPTIONS") {
      return res.status(204).end();
    }
    return corsMiddleware(req, res, next);
  };
}

module.exports = { createCorsMiddleware, collectAllowedOrigins, applyCorsHeaders };
