// server.js

const fs = require('fs');
const path = require('path');

// Check if .env exists, if not create from example
const envPath = path.join(__dirname, '.env');
const envExamplePath = path.join(__dirname, '.env.example');

if (!fs.existsSync(envPath)) {
  if (fs.existsSync(envExamplePath)) {
    console.log('⚠️  .env file not found, creating from .env.example');
    fs.copyFileSync(envExamplePath, envPath);
    console.log('✅ .env file created successfully');
  } else {
    console.error('❌ Neither .env nor .env.example found!');
  }
}

// Now load the environment variables
require('dotenv').config({ path: envPath });

// require('dotenv').config();
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const { sequelize } = require('./models');

const app = express();

const PORT = process.env.PORT || 3000;


// Import M-Pesa configuration and service
const mpesaConfig = require('./config/mpesaConfig');
const { initializeMpesaService } = require('./services/mpesaService');

// 2. Configure CORS BEFORE other middleware
app.use(cors({
  origin: [
    'http://localhost:5173',  // Vite default
    'http://localhost:3000',  // React default
    'http://localhost:5174',  // Alternative Vite port
    'http://127.0.0.1:5173',
    // Add your production domain here
  ],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));


app.use(
  helmet({
    crossOriginResourcePolicy: { policy: "cross-origin" },
  })
);


// Import routes
const authRoutes = require('./routes/authRoutes');
const userRoutes = require('./routes/userRoutes');
const storeRoutes = require('./routes/storeRoutes');
const registerRoutes = require('./routes/registerRoutes');
const categoryRoutes = require('./routes/categoryRoutes');
const brandRoutes = require('./routes/brandRoutes');
const productRoutes = require('./routes/productRoutes');
const inventoryRoutes = require('./routes/inventoryRoutes');
const supplierRoutes = require('./routes/supplierRoutes');
const purchaseOrderRoutes = require('./routes/purchaseOrderRoutes');
const transactionRoutes = require('./routes/transactionRoutes');
const customerRoutes = require('./routes/customerRoutes');
const discountRoutes = require('./routes/discountRoutes');
const salesRoutes = require('./routes/saleRoutes');
const returnRoutes = require('./routes/returnRoutes');
const cashDrawerRoutes = require('./routes/cashDrawerRoutes');
const reportRoutes = require('./routes/reportRoutes');

const mpesaRoutes = require('./routes/mpesaRoutes');

const orderRoutes = require('./routes/orderRoutes');

const shoppingRoutes = require('./routes/shoppingRoutes');




// Import middleware
const errorHandler = require('./middleware/errorHandler');








app.use(morgan('dev')); // HTTP request logger
app.use(express.json()); // Parse JSON bodies
app.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies

app.use(express.static('public'));

app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// Initialize M-Pesa service on server startup
try {
  initializeMpesaService(mpesaConfig);
  console.log('✅ M-Pesa service initialized successfully');
} catch (error) {
  console.error('❌ Failed to initialize M-Pesa service:', error.message);
  process.exit(1); // Exit if M-Pesa config is invalid
}

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ 
    status: 'OK', 
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

// API Routes
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/stores', storeRoutes);
app.use('/api/registers', registerRoutes);
app.use('/api/categories', categoryRoutes);
app.use('/api/brands', brandRoutes);
app.use('/api/products', productRoutes);
app.use('/api/inventory', inventoryRoutes);
app.use('/api/suppliers', supplierRoutes);
app.use('/api/purchase-orders', purchaseOrderRoutes);
app.use('/api/transactions', transactionRoutes);
app.use('/api/customers', customerRoutes);
app.use('/api/discounts', discountRoutes);
app.use('/api/sales', salesRoutes);
app.use('/api/returns', returnRoutes);
app.use('/api/cash-drawer', cashDrawerRoutes);
app.use('/api/reports', reportRoutes);
app.use('/api/mpesa', mpesaRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/shopping', shoppingRoutes);



// 404 handler
app.use((req, res) => {
  res.status(404).json({ message: 'Route not found' });
});

// Error handling middleware (must be last)
// app.use(errorHandler);

// Database connection and server start
const startServer = async () => {
  try {
    // Test database connection
    await sequelize.authenticate();
    console.log('✅ Database connection established successfully.');

    // Sync models (use { force: false } in production)
    await sequelize.sync({ alter: false });
    console.log('✅ Database models synchronized.');

    // Start server
    app.listen(PORT, () => {
      console.log(`🚀 Server is running on port ${PORT}`);
      console.log(`📍 Environment: ${process.env.NODE_ENV || 'development'}`);
      console.log(`🔗 API Base URL: http://localhost:${PORT}/api`);
      console.log(`💾 BASE API URL IS: ${process.env.API_URL}`);
    });
  } catch (error) {
    console.error('❌ Unable to start server:', error);
    process.exit(1);
  }
};

startServer();

// Graceful shutdown
process.on('SIGTERM', async () => {
  console.log('SIGTERM signal received: closing HTTP server');
  await sequelize.close();
  process.exit(0);
});

process.on('SIGINT', async () => {
  console.log('SIGINT signal received: closing HTTP server');
  await sequelize.close();
  process.exit(0);
});

module.exports = app;