require('dotenv').config();
const express = require('express');
const cors = require('cors');
const apiRoutes = require('./routes/apiRoutes');
const userRoutes = require('./routes/userRoutes');
const https = require('https');
const fs = require("fs")

const {initWebSocket} = require('./services/webSocket')
const app = express();
const sslOptions = {
  // key: fs.readFileSync('./certificates/fullchain.pem'),
  // cert: fs.readFileSync('./certificates/privkey.pem'),
};
// Create HTTP server (use HTTP for now to avoid SSL issues, in production use HTTPS with valid certificates)
const server = require('http').createServer(app);

// Initialize WebSocket server
initWebSocket(server);
console.log('WebSocket server initialized');
// Middleware to parse JSON bodies
app.use(express.json()); // 👈 Add this line

// Serve static files from the public directory
app.use(express.static('public'));

// CORS Configuration
const allowedOrigins = ['https://guardiancalls.tech4bizsolutions.com','http://localhost:5174', 'https://yourfrontend.com','http://localhost:5173', 'http://192.168.1.35:5173']; // Replace as needed

app.use((req, res, next) => {
  // Check if the request is for the WebSocket test page
  if (req.path === '/websocket-test' || req.path === '/public/websocket-test.html') {
    // Less restrictive CSP for WebSocket test page
    res.setHeader(
      'Content-Security-Policy',
      "default-src 'self'; connect-src 'self' ws: wss: http: https:; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';"
    );
  } else {
    // Original CSP for other pages
    res.setHeader(
      'Content-Security-Policy',
      "default-src 'self'; connect-src 'self' wss://guardiancalls.tech4bizsolutions.com https://your-api-domain.com; script-src 'self';"
    );
  }
  next();
});


app.use(cors({
  origin: function (origin, callback) {
    if (!origin) return callback(null, true); // Allow requests with no origin
    if (allowedOrigins.indexOf(origin) === -1) {
      const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
      return callback(new Error(msg), false);
    }
    return callback(null, true);
  },
  optionsSuccessStatus: 200
}));

// Routes
app.use('/api/user', userRoutes);
app.use('/api/call-list', apiRoutes);

app.get('/', (req, res) => {
  res.send("Backend is working!");
});

// WebSocket test page
app.get('/websocket-test', (req, res) => {
  res.sendFile(__dirname + '/public/websocket-test.html');
});

// Start server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`HTTP server running on port ${PORT}`);
  console.log(`WebSocket server available at ws://localhost:${PORT}`);
});
