var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
// var mongoose = require("mongoose");
// var stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
var cors = require('cors');
require("dotenv").config();
const rateLimit = require('express-rate-limit');
const controllers = require('./Controller/index');
const authmiddleware= require('./middleware/auth')
// Import User and Company models from model/index.js
// const { User, Company } = require('./'); // Adjust the path as necessary
// const model = require('./Model/index');
const connectDB = require('./config/db');


var app = express();

// CORS configuration
app.use(cors());

connectDB();

// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 1000, // Limit each IP to 1 request per `windowMs`
  message: "Too many requests, please try again later.",
});

// app.use('/api/data/getHtmlPage/', apiLimiter);  

// Route with authentication and rate limiting
// app.get("/getHtmlPage/:vin",apiLimiter,  authmiddleware.authenticate("jwt", { session: false }), controllers.HtmlDataController.fetchAndSaveHtml);

app.use('/', apiLimiter, indexRouter);

// Webhook route


// Catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// Error handler
app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;