import mongoose, { Connection } from "mongoose";
import { MONGODB_CONNECTION_STRING } from "./environment";
import { ensureWalletTransactionIndexes } from "../models/WalletTransactionModel";
import { ensureNotificationIndexes } from "../models/NotificationModel";

let databaseInstance: Connection | null = null;

export const connectDB = async (): Promise<void> => {
  try {
    mongoose.set('strictQuery', true);

    if (!MONGODB_CONNECTION_STRING) {
      console.error(
        "MongoDB connection error: DB_URI/MONGODB_URI/DATABASE_URL is not set."
      );
      process.exit(1);
    }

    const connection = await mongoose.connect(MONGODB_CONNECTION_STRING);
    databaseInstance = connection.connection;

    console.log("MongoDB Connected...");

    // Repair the WalletTransaction indexes (drops legacy sparse-unique indexes
    // that incorrectly treated `null` as a value, which silently broke every
    // second top-up per user). Idempotent — safe to run on every startup.
    try {
      await ensureWalletTransactionIndexes();
    } catch (e) {
      console.error(
        "[startup] ensureWalletTransactionIndexes failed:",
        e instanceof Error ? e.message : e
      );
    }

    try {
      await ensureNotificationIndexes();
    } catch (e) {
      console.error(
        "[startup] ensureNotificationIndexes failed:",
        e instanceof Error ? e.message : e
      );
    }
  } catch (err: any) {
    console.error("MongoDB connection error:", err.message);
    process.exit(1);
  }
};

export const getDatabaseInstance = (): Connection | null => {
  return databaseInstance;
};

export default connectDB;
