require('dotenv').config();
const express = require('express');
const cors = require('cors');
const session = require('express-session');

// Import Modular Routes
const authRoutes = require('./routes/auth');
const productRoutes = require('./routes/product');
const salesRoutes = require('./routes/sales');
const stockRoutes = require('./routes/stock_status');

const app = express();

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

// Inside src/server.js - Update your CORS configuration to match Vite:
app.use(cors({
    origin: 'http://localhost:5173', // Change this from 3000 to 5173
    credentials: true
}));

app.use(session({
    secret: process.env.SESSION_SECRET || 'dab_enterprise_secret_2026',
    resave: false,
    saveUninitialized: false,
    cookie: { 
        maxAge: 1000 * 60 * 60, // 1 hour session window
        secure: false // Set to true if you ever run over production HTTPS
    }
}));

// Bind Application Routes
app.use('/api/auth', authRoutes);
app.use('/api/products', productRoutes);
app.use('/api/sales', salesRoutes);
app.use('/api/stock', stockRoutes);

// Server Entry Check
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`🚀 Server successfully deployed on port ${PORT}`);
});