const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require("cors");
const generalRoutes = require("./routes/generalRoutes");
const authRoutes = require("./routes/authRoutes");
const userRoutes = require("./routes/userRoutes");
const eventRoutes = require("./routes/eventRoutes");
const adRoutes = require("./routes/adRoutes");
const adGroupRoutes = require("./routes/adGroupRoutes");
const scriptRoutes = require("./routes/scriptRoutes");
require("dotenv").config();

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

// Import the database connection
const db = require('./config/db'); // Ensure the correct path

const app = express();
const server = http.createServer(app);
// const io = socketIo(server);

const io = socketIo(server, {
  cors: {
    origin: [
      "http://localhost:3000",       // Allow connections from localhost (development)
      "https://bigscreensocial.app"  // Allow connections from production site
    ],
    methods: ["GET", "POST"], // Allowed methods
    allowedHeaders: ["Content-Type"], // Optional: You can add headers you want to allow
    credentials: true // Enable cookies/credentials (optional)
  }
});

const clients = {}; // Store client sockets by pairing ID
app.use(cors());
app.use(express.json());

// Helper function to write logs to a file
const logToFile = (message) => {
  const logMessage = `${new Date().toISOString()} - ${message}\n`;
  const logFilePath = path.join(__dirname, 'logs', 'server.log'); // Ensure the logs directory exists

  // Check if the 'logs' directory exists, if not, create it
  if (!fs.existsSync(path.dirname(logFilePath))) {
    try {
    fs.mkdirSync(path.dirname(logFilePath), { recursive: true });
  } catch (error) {
    // console.error("Error creating log directory:", error);
  }
  }

  // Append log message to the file
  fs.appendFileSync(logFilePath, logMessage, 'utf8');
};


// Socket Main - START

// io.on('connection', (socket) => {
//   console.log('A user connected');
//   logToFile('Client connected: ' + socket.id);
  
//   // Handle any incoming events from the frontend
//   socket.on('disconnect', () => {
//     console.log('User disconnected');
//      logToFile(`Client disconnected: ${socket.id}, Reason: ${reason}`);
//   });
// });


// When a client connects
io.on('connection', (socket) => {
    // console.log('Client connected');
    
    // logToFile('Client connected: ' + socket.id);

    socket.on('disconnect', (reason) => {
        // logToFile(`Client disconnected: ${socket.id}, Reason: ${reason}`);

    });
    
    // Handle reconnecting (this is on the server side, mostly for debugging purposes)
    socket.on('reconnect', () => {
        // logToFile(`Client reconnected: ${socket.id}`);
    });

    socket.on('reconnect_attempt', (attemptNumber) => {
        // logToFile(`Reconnection attempt #${attemptNumber} for client ${socket.id}`);
    });
});

// Socket Main - END

// Emit to Socket - START

// Endpoint to emit event to a specific socket by socketId
app.post("/api/emit-new-event-post", (req, res) => {
    const { post, event_id } = req.body;

    if (!event_id || !post) {
        return res.status(400).json({ message: "Event ID and post are required." });
    }
    
    // logToFile(`Emitted ${event_id} for data  ${post} `);

    try {
     
         io.emit('newEventPost', {
          ...post,
          event_id: event_id, // Send event identifier along with the post
        });


        res.status(200).json({ message: "Event emitted successfully" });
    } catch (error) {
        console.error("Error emitting event:", error);
        res.status(500).json({ message: "An error occurred while emitting the event." });
    }
});
// Emit to Socket - END

// Routes
app.get('/', (req, res) => {
    res.status(400).send('Homepage');
});

app.use("/api/auth", authRoutes); // Authentication route
app.use("/api/general", generalRoutes); // Authentication route
app.use("/api/users", userRoutes);
app.use("/api/events", eventRoutes);
app.use("/api/ads", adRoutes);
app.use("/api/ads-group", adGroupRoutes);
app.use("/api/scripts", scriptRoutes);

server.listen(3000, () => {
    console.log('Server is running on port 3000');
});
