require("dotenv").config();
const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();
const cors = require('cors');
const projectsRoutes = require('./routes/projects'); // Import the projects routes
const activityRoutes = require('./routes/activity');
const contactRoutes = require('./routes/contact');
const skillsRoutes = require('./routes/skills');
const introRoutes = require('./routes/intro');
const aboutRoutes = require('./routes/about');

// Set up SSL certificate files
const options = {
  key: fs.readFileSync(process.env.SSL_KEY_PATH),
  cert: fs.readFileSync(process.env.SSL_CERT_PATH),
};

const ORIGIN = process.env.ORIGIN ? process.env.ORIGIN.split(",") : [];

console.log("ORIGIN:", ORIGIN);

// CORS configuration
const corsOptions = {
  origin: process.env.ORIGIN ? process.env.ORIGIN.split(",") : [],
  methods: 'GET,POST,PUT,DELETE',
  credentials: true,
};

// Middleware to parse JSON request bodies
app.use(express.json());

// Enable CORS
app.use(cors(corsOptions));

// Middleware to set Last-Modified header
app.use((req, res, next) => {
  res.setHeader('Last-Modified', new Date().toUTCString());
  next();
});

// Use the routes
app.use('/', projectsRoutes);
app.use('/', activityRoutes);
app.use('/', contactRoutes);
app.use('/', skillsRoutes);
app.use('/', introRoutes);
app.use('/', aboutRoutes);

// Start the HTTPS server
https.createServer(options, app).listen(process.env.PORT, () => {
  console.log(`Server is running on: ${process.env.BASE_URL}:${process.env.PORT}`);
});