import dotenv from 'dotenv';
dotenv.config();

import app from './app.js';
import connectDB from './config/db.js';
import mongoose from 'mongoose';

const PORT = process.env.PORT || 5000;
const isProd = process.env.NODE_ENV === 'production';

if (isProd && (!process.env.JWT_SECRET || process.env.JWT_SECRET.length < 32)) {
  console.warn('WARNING: JWT_SECRET is missing or too short for production. Set a strong 32+ char secret.');
}
if (isProd && (!process.env.MONGODB_URI || !/mongodb(\+srv)?:\/\//.test(process.env.MONGODB_URI))) {
  console.error('FATAL: MONGODB_URI is not set correctly for production.');
  process.exit(1);
}

const server = connectDB().then(() => {
  return new Promise((resolve) => {
    const listener = app.listen(PORT, () => {
      console.log(`Server running on port ${PORT} (${isProd ? 'production' : 'development'})`);
      resolve(listener);
    });
  });
});

const shutdown = async (signal) => {
  console.log(`${signal} received. Shutting down gracefully...`);
  try {
    const listener = await server;
    if (listener && listener.close) {
      await new Promise((resolve) => listener.close(resolve));
    }
    if (mongoose.connection.readyState === 1) {
      await mongoose.connection.close();
    }
    process.exit(0);
  } catch (err) {
    console.error('Error during shutdown:', err.message);
    process.exit(1);
  }
};

process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));

process.on('unhandledRejection', (reason) => {
  console.error('Unhandled rejection:', reason instanceof Error ? reason.stack : reason);
});
