const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
require('dotenv').config();

const { connectDB, sequelize } = require('./config/db');
const { initSubscriptionJob } = require('./jobs/subscription_job');
const { initCrmImportJob } = require('./jobs/crm_import_job');
const routes = require('./routes');

// Start Automated Tasks
initSubscriptionJob();
initCrmImportJob();

const app = express();
const PORT = process.env.PORT || 5000;

// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Routes
app.use('/uploads', express.static('uploads'));
app.use('/api', routes);

// Global Error Handler
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    message: 'Internal Server Error',
    error: process.env.NODE_ENV === 'development' ? err.message : {}
  });
});

// Database Connection and Server Start
connectDB().then(() => {
  // Sync models (this creates tables if they don't exist)
  sequelize.sync({ force: false }).then(() => {
    console.log('✅ Database synchronization complete.');
    app.listen(PORT, () => {
      console.log(`🚀 Server running on port ${PORT} in ${process.env.NODE_ENV} mode`);
    });
  });
});