    const path = require('path');

const { products } = require('./data/product-data.js');
let { messages, messageCount } = require('./data/product-data.js');
const PORT = 3000;

// Get the Express object
const express = require('express');
const app = express();            

app.set('view engine', 'pug');                   // Set up Pug as the view engine
app.set('views', path.join(__dirname, 'views')); // Tell Express where the views are


// Handle URL-encoded request queries (needed for the contact/message post requests)
app.use(express.urlencoded({ extended: false }));

// Serve static files 
app.use(express.static(__dirname));

// Route: Home
app.get(['/', '/home', '/index'], (req, res) => {
  res.render('pages/index', { products, currentPage: 'home' });
});

// Route: About
app.get('/about', (req, res) => {
  res.render('pages/about', { products, currentPage: 'about' });
});

// Route: Contact
app.get('/contact', (req, res) => {
  res.render('pages/contact', { products, currentPage: 'contact' });
});

// Route: Products
app.get('/products', (req, res) => {
  res.render('pages/products', { products, currentPage: 'products' });
});

// Route: Individual Product (via query string ?id=1)
app.get('/product', (req, res) => {
  const id = parseInt(req.query.id);
  const prod = products[id - 1];

  if (!prod) {
    return res.status(404).send('Product not found');
  }

  res.render('pages/product', { prod, currentPage: 'products' });
});

// Route: contact/message post
app.post('/contact/message', (req, res) => {
    messages.push(req.body);
    messageCount++;
    res.render('pages/messageReceived');
});

// 404 fallback
app.use((req, res) => {
  res.status(404).send('Not Found');
});

// Start server
app.listen(PORT);
console.log(`Server is listening at http://localhost:${PORT}`);