const path = require('path');
const express = require("express");
const https = require('https');
const http = require('http');
const app = express();
const useragent = require('express-useragent');
const userAg = require('useragent');
require('dotenv').config();
const logger = require('./helpers/logger');
const dbLogger = require("./helpers/dbLogger");
const { queryDb } = require("./helpers/db");
const bodyParser = require('body-parser');

const session = require('express-session');
// const verifyRecaptcha = require('./helpers/recaptcha')

const isOnePageOnly = true


// // Error handling middleware
// app.use((err, req, res, next) => {
//   // logger.error(err.stack); // Log the error
//   logger.error(err); // Log the error
//   res.status(500).send('Internal Server Error'); // Respond with an error message
// });

logger.info('First connection');



// Express error middleware to catch and log errors
function errorMiddleware(err, req, res, next) {
  logger.error(err.stack);
  res.status(500).send('Internal Server Error');
}

//middlewares
app.use(useragent.express());

app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
app.set("view engine", "ejs");


app.use(session({
  secret: 'd23o4ma_da.as/f,-sdfg/2341dfdgdsa',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false } // Set to true if using HTTPS
}));

// // Endpoint for verifying reCAPTCHA token
// app.post('/verify-recaptcha', async (req, res) => {
//   const token = req.body.recaptchaToken; // Access the reCAPTCHA token from the request body

//   // Verify the token using the verifyRecaptcha function from the recaptcha.js file
//   const { success, score } = await verifyRecaptcha(token);

//   if (success && score >= 0.5) {
//     res.json({ success: true, message: 'reCAPTCHA verification passed' });
//   } else {
//     res.json({ success: false, message: 'reCAPTCHA verification failed' });
//   }
// });


const detectVPN = (req, res, next) => {
  const { isBot, isMobile, isDesktop, isTablet, isSmartTV, isConsole, browser } = req.useragent;
  const isVPN = isDesktop && !isBot && !isMobile && !isTablet && !isSmartTV && !isConsole && browser === 'Chrome';
  req.isConsole = isConsole;
  req.isVPN = isVPN;

  // next();
};

// Custom middleware function to be executed for every GET request
const logDbMiddleware = (req, res, next) => {
  try {
    detectVPN(req, res);

    dbLogger(req);
    next();
  } catch (err) {
    next(err);
  }

  // detectVPN(req, res, next);
  // dbLogger(req);
  // next();
};

// Custom middleware function to block IP addresses in the BlockedIPs table
const blockIPMiddleware = async (req, res, next) => {
  try {
    const visitorIp = req.headers['x-forwarded-for'] ? req.headers['x-forwarded-for'].split(',')[0] : req.connection.remoteAddress;
    // const visitorIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    const searchQuery = `SELECT * FROM BlockedIPs WHERE ip = '${visitorIp}'`;
    const rows = await queryDb(searchQuery);
    // logger.info(`Checking if ip is blocked: ${visitorIp}`);

    if (rows.length > 0) {
      // IP address found in BlockedIPs table, block the request
      logger.info(`Blocked IP: ${visitorIp}`);
      res.status(403).send('Forbidden');
    } else {
      // IP address not found, proceed to the next middleware
      logger.info(`Ip is NOT blocked: ${visitorIp}`);
      next();
    }
  } catch (error) {
    logger.error('Error checking IP:', error);
    res.status(500).send('Internal Server Error');
  }
};

app.use((req, res, next) => {
  if (req.method === 'GET') {
    logDbMiddleware(req, res, next);
  } else {
    next();
  }
});

//routes

app.use(require("./routes/loginRoutes"));
app.use(require("./routes/indexRoutes"));

if (process.env.ONE_PAGE_ONLY === 'false') {
  app.use('/locations', require("./routes/locationRoutes"));
  app.use('/', require("./routes/keywordRoutes"));
  app.use('/leads', require("./routes/leadRoutes"));

  // app.use('/blog', require("./routes/blogRoutes"));





}

// app.use('/email', require("./routes/emailRoutes"));

// This route will handle all the requests that are not handled by any other route handler.
app.all('*', (req, res) => {
  res.status(404).render("pages/404View");
});

// Register the error middleware
app.use(errorMiddleware);



//server config
http.createServer(app).listen(process.env.PORT ?? 80, () => {
  console.log('listening on port ' + (process.env.PORT ?? 80))
  logger.info('listening on port: ' + (process.env.PORT ?? 80));
});

