require('dotenv').config();
const express = require("express");
const logActivity = require("./middleware/apiLogger");
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const cron = require('node-cron');
var cors = require('cors');

const app = express();

// Increase timeout for large file uploads
app.use((req, res, next) => {
  req.setTimeout(300000); // 5 minutes
  res.setTimeout(300000); // 5 minutes
  next();
});

app.use(cors({
  origin: [
    'http://localhost:5173', // Vite dev server
    'https://thestaymaster.com', 
    'https://bms.thestaymaster.com', 
    'https://staymaster-website.vercel.app',
    'http://localhost:4200',
    'http://localhost:8081', // React Native Metro bundler
    'http://10.0.2.2:8080', // Android emulator to host machine
    'http://10.0.3.2:8080', // Genymotion emulator to host machine
    'http://127.0.0.1:8080' // iOS simulator to host machine
  ],
  credentials: true
}));

// Set consistent 5MB limits for all file uploads and JSON parsing
app.use(express.json({ limit: '5mb' }));
app.use(express.urlencoded({ extended: true, limit: '5mb' }));
app.use(bodyParser.json({ limit: '5mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '5mb' }));
app.use(cookieParser());

const port = process.env.PORT || 8080;
app.set('view engine','ejs');
app.use('/api/public',express.static('public'));

app.all('*', logActivity);
app.use('/api/ext', require('./routes/apiRoutes'));
app.use('/api/contacts', require("./routes/contactRoutes"));
app.use('/api/destinations', require("./routes/destinationRoutes"));
app.use('/api/users', require('./routes/userRoutes'));
app.use('/api/feusers', require('./routes/feuserRoutes'));
app.use('/api/collections', require('./routes/collectionRoutes'));
app.use('/admin', require('./routes/backendRoutes'));
app.use('/api/hosts', require('./routes/hostRoutes'));
app.use('/api/settings', require('./routes/settingsRoutes'));
app.use('/api/properties', require('./routes/propertyRoutes'));
// console.log("Attempting to load blogRoutes."); // Add this log
try {
  app.use('/api/blogs', require('./routes/blogRoutes'));
  // console.log("blogRoutes loaded successfully.");
} catch (error) {
  console.error("Error loading blogRoutes:", error);
}

// Global error handler - must be registered after all routes
const { errorHandler } = require('./middleware/errorHandler');
app.use(errorHandler);

// Initialize Live Booking Sync Service
const LiveBookingSyncService = require('./services/liveBookingSyncService');
const liveBookingSyncService = new LiveBookingSyncService();

// Schedule cron job to sync live booking data every 30 minutes
// Cron expression: */30 * * * * means "every 30 minutes"
cron.schedule('*/30 * * * *', async () => {
    // console.log('\n=== [Cron Job] Starting scheduled live booking sync ===');
    try {
        // Sync all data from 2025-10-01 in 15-day batches
        await liveBookingSyncService.syncAllData();
        // console.log('=== [Cron Job] Live booking sync completed ===\n');
    } catch (error) {
        console.error('=== [Cron Job] Error during live booking sync:', error);
    }
});

// console.log('Live booking sync cron job scheduled: Every 30 minutes');

// Run initial sync on server startup
(async () => {
    try {
        // console.log('\n=== [Startup] Running initial live booking sync... ===');
        await liveBookingSyncService.syncAllData();
        // console.log('=== [Startup] Initial live booking sync completed ===\n');
    } catch (error) {
        console.error('=== [Startup] Error during initial live booking sync:', error);
        console.error('You can manually trigger sync from the admin panel ===\n');
    }
})();

app.listen(port, () => {
    console.log(`app running on port ${port}`);
});