const { MongoClient } = require('mongodb');
require('dotenv').config();

const dbUser = process.env.DB_USER;
const dbPassword = process.env.DB_PASSWORD;
const dbHost = process.env.DB_HOST || 'localhost';
const dbPort = process.env.MONGODB_PORT || 27017;

let mongoUri = process.env.MONGODB_URI;

if (!mongoUri) {
  // Default: try without auth first (MongoDB often runs without auth in dev)
  mongoUri = `mongodb://${dbHost}:${dbPort}`;
}

const dbName = process.env.DB_NAME || process.env.MONGODB_DB || 'smartshop_db';

let client;
let db;

async function getDb() {
  if (db) return db;
  
  if (!client) {
    client = new MongoClient(mongoUri);
    try {
      await client.connect();
      console.log('✅ MongoDB connected:', mongoUri);
    } catch (err) {
      console.error('❌ MongoDB connection failed:', err.message);
      throw err;
    }
  }
  
  db = client.db(dbName);
  return db;
}

function getCollectionName(base) {
  return base;
}

async function getCollections() {
  const _db = await getDb();
  return {
    users: _db.collection(getCollectionName('users')),
    customers: _db.collection(getCollectionName('customers')),
    products: _db.collection(getCollectionName('products')),
    sales: _db.collection(getCollectionName('sales')),
    counters: _db.collection(getCollectionName('counters'))
  };
}

async function getNextSequence(collectionName) {
  const { counters } = await getCollections();

  const res = await counters.findOneAndUpdate(
    { _id: collectionName },
    { $inc: { seq: 1 } },
    { upsert: true, returnDocument: 'after' }
  );

  return res.value?.seq || 1;
}

async function closeMongo() {
  try {
    if (client) await client.close();
  } catch (_) {}
}

module.exports = {
  getDb,
  getCollections,
  getNextSequence,
  closeMongo
};
