import cors from "cors";

export const allowedOrigins = [
	"*.alpla.net",
	"http://localhost:4173",
	"http://localhost:4200",
	"http://localhost:3000",
	"http://localhost:3001",
	"http://localhost:4000",
	"http://localhost:4001",
	"http://localhost:5500",
	"http://localhost:8081",
	"https://admin.socket.io",
	"https://electron-socket-io-playground.vercel.app",
	`${process.env.URL}`,
	`http://${process.env.PROD_SERVER}:3000`,
	`http://${process.env.PROD_SERVER}:3100`, // temp
	`http://usmcd1olp082:3000`,
	`${process.env.EXTERNAL_URL}`, // internal docker
	"chrome-extension://mddoackclclnbkmofficmmepfnadolfa",
];
export const lstCors = () => {
	return cors({
		origin: (origin, callback) => {
			//console.log("CORS request from origin:", origin);

			if (!origin) return callback(null, true); // allow same-site or direct calls

			try {
				const hostname = new URL(origin).hostname; // strips protocol/port
				//console.log("Parsed hostname:", hostname);

				if (allowedOrigins.includes(origin)) {
					return callback(null, true);
				}

				// Now this works for *.alpla.net
				if (hostname.endsWith(".alpla.net") || hostname === "alpla.net") {
					return callback(null, true);
				}
			} catch (_) {
				//console.error("Invalid Origin header:", origin);
			}

			return callback(new Error(`Not allowed by CORS: ${origin}`));
		},
		methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
		credentials: true,
		exposedHeaders: ["set-cookie", "expo-protocol-version", "expo-sfv-version"],
		allowedHeaders: [
			"Content-Type",
			"Authorization",
			"X-Requested-With",
			"XMLHttpRequest",
			"expo-runtime-version",
			"expo-platform",
			"expo-channel-name",
			"*",
		],
	});
};
