const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
require('dotenv').config();

// NEW: Import http and socket.io
const http = require('http');
const { Server } = require('socket.io'); // Destructure Server from socket.io

// Your existing route imports
const labourRoutes = require('./routes/labourRoutes');
const adminRoutes = require('./routes/adminRoutes');
const workOrderRoutes = require('./routes/workOrderRoutes');
const customerRoutes = require('./routes/customerRoutes');
const paymentRoutes = require('./routes/paymentRoutes');

const app = express();
app.use(cors());
app.use(express.json());

// --- NEW CODE STARTS HERE: Socket.IO Setup ---
const server = http.createServer(app); // Create an HTTP server using your Express app
const io = new Server(server, {
    cors: {
        origin: "*", // Allow your frontend to connect
        methods: ["GET", "POST"]
    }
});

// Pass the 'io' instance to your request/response cycle
// This makes 'req.app.io' available in your route handlers and controllers
app.set('io', io);

// Basic Socket.IO connection handling (you'll expand this in your controllers)
io.on('connection', (socket) => {
    console.log(`A user connected: ${socket.id}`);

    // Example: Joining rooms (important for targeted updates)
    // You'll likely want to emit this from your frontend after login/auth
    socket.on('joinRoom', (roomName) => {
        socket.join(roomName);
        console.log(`Socket ${socket.id} joined room: ${roomName}`);
    });

    socket.on('disconnect', () => {
        console.log(`User disconnected: ${socket.id}`);
    });

    // You can add more general-purpose socket event listeners here
    // For specific business logic (like order updates), it's better to
    // emit from your controllers after database operations.
});
// --- NEW CODE ENDS HERE ---

// --- Existing Code for uploads directory ---
const uploadsDir = path.join(__dirname, 'uploads', 'images');
if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
}
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// --- End Existing Code ---

mongoose.connect(process.env.MONGO_URI, {
    // useNewUrlParser: true, // Deprecated, remove if using Mongoose 6+
    // useUnifiedTopology: true, // Deprecated, remove if using Mongoose 6+
})
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('MongoDB connection error:', err));

// Routes
// Note: Multer `upload` middleware is typically defined and used directly in `labourRoutes.js`
app.use('/api/labour', labourRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/workorders', workOrderRoutes);
app.use('/api/customers', customerRoutes);
app.use('/api/payments', paymentRoutes);

// Root route
app.get("/", (req, res) => {
    res.send("API is running");
});

const PORT = process.env.PORT || 5000;
// Change app.listen to server.listen
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));