require('module-alias/register');
const mongoose = require('mongoose');
const { registerAllModels } = require('./models/registerAll');
const { loadEnv, validateEnv, getRuntimeConfig } = require('./config/env');

// Make sure we are running node 7.6+
const [major, minor] = process.versions.node.split('.').map(parseFloat);
if (major < 20) {
  console.log('Please upgrade your node.js version at least 20 or greater. 👌\n ');
  process.exit();
}

// import environmental variables from our variables.env file
loadEnv();
const runtime = getRuntimeConfig(process.env);
const envIssues = validateEnv(process.env);
if (envIssues.length) {
  console.error('Environment validation failed:');
  envIssues.forEach((issue) => console.error(`- ${issue}`));
  process.exit(1);
}

mongoose.connect(runtime.database, { serverSelectionTimeoutMS: 10000 });

const OPENAI_API_KEY = process.env.OPENAI_API_KEY;

mongoose.connection.on('error', (error) => {
  console.log(
    `1. 🔥 Common Error caused issue → : check your .env file first and add your mongodb url`
  );
  console.error(`2. 🚫 Error → : ${error.message}`);
});
registerAllModels();

// Start our app!
const app = require('./app');
const { startAutomationWorker, startAgentWorker } = require('./services/automation/worker');
app.set('port', runtime.port);
const server = app.listen(app.get('port'), () => {
  startAutomationWorker();
  startAgentWorker();
  console.log(`Express running → On PORT : ${server.address().port}`);
});
