"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const mongoose_1 = __importDefault(require("mongoose"));
const dotenv_1 = __importDefault(require("dotenv"));
const dns_1 = __importDefault(require("dns"));
dotenv_1.default.config();
const IS_PRODUCTION = process.env.IS_PRODUCTION === "true";
const MONGO_URI = IS_PRODUCTION ? process.env.MONGO_URI_PROD : process.env.MONGO_URI_DEV;
const DNS_SERVERS = process.env.DNS_SERVERS || "8.8.8.8,1.1.1.1";
const connectDB = async () => {
    if (!MONGO_URI) {
        console.error(`MONGO_URI is not defined for ${IS_PRODUCTION ? "production" : "development"} mode in .env file`);
        process.exit(1);
    }
    if (MONGO_URI.startsWith("mongodb+srv://")) {
        const servers = DNS_SERVERS.split(",")
            .map((item) => item.trim())
            .filter(Boolean);
        if (servers.length > 0) {
            dns_1.default.setServers(servers);
        }
    }
    const connectionOptions = {
        family: 4,
        serverSelectionTimeoutMS: 10000,
    };
    try {
        await mongoose_1.default.connect(MONGO_URI, connectionOptions);
        console.log(`MongoDB Connected (${IS_PRODUCTION ? "production" : "dev"})`);
    }
    catch (err) {
        console.error("MongoDB Connection Error: ", err);
        if (err.code === "ECONNREFUSED" && MONGO_URI.startsWith("mongodb+srv://")) {
            console.error("SRV DNS lookup failed. Keep using MONGO_URI in .env, but switch it to Atlas standard mongodb:// connection string (non-SRV) or set DNS_SERVERS in .env.");
        }
        process.exit(1);
    }
};
exports.default = connectDB;
