import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import { createRoutes } from './src/routes/index.js';
import { aircallConfig } from './src/config/aircall.config.js';
import { connectMongoDB } from './src/utils/db.js';
import { createRedisClient } from './src/utils/redis.js';
import { createLogger } from './src/utils/logger.js';

// Get directory name in ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Load environment variables from the correct path
dotenv.config({ path: path.resolve(__dirname, '.env') });

// Validate required environment variables
const requiredEnvVars = ['AIRCALL_API_ID', 'AIRCALL_API_TOKEN', 'MONGODB_URI', 'REDIS_URL'];
const missingEnvVars = requiredEnvVars.filter(envVar => !process.env[envVar]);

if (missingEnvVars.length > 0) {
  console.error('Missing required environment variables:', missingEnvVars);
  process.exit(1);
}

const app = express();
const port = process.env.AIRCALL_PORT || 3002;
const logger = createLogger('aircall-server');

// Middleware
app.use(cors());
app.use(express.json());

// Connect to databases
let mongodb;
let redis;

async function initializeServer() {
  try {
    // Connect to MongoDB
    mongodb = await connectMongoDB();
    logger.info('Connected to MongoDB');

    // Connect to Redis
    redis = await createRedisClient();
    logger.info('Connected to Redis');

    // Initialize configs with database connections
    const configs = {
      aircall: {
        ...aircallConfig,
        mongodb,
        redis,
        logger
      }
    };

    // Initialize routes
    const routes = createRoutes(configs, logger);
    app.use('/api', routes);

    // Error handling middleware
    app.use((err, req, res, next) => {
      logger.error('Server error:', err);
      res.status(500).json({
        error: 'Internal server error',
        message: err.message
      });
    });

    // Start server
    app.listen(port, () => {
      logger.info(`Aircall server listening on port ${port}`);
    });
  } catch (error) {
    logger.error('Failed to initialize server:', error);
    process.exit(1);
  }
}

initializeServer(); 