const http = require('http');
const fs = require('fs');
const url = require('url');
const path = require('path');
const ejs = require('ejs'); 

const { products } = require('./data/product-data.js');

const PORT = 3000;
const mimeTypes = {
  '.html': 'text/html',
  '.css':  'text/css',
  '.js':   'application/javascript',
  '.png':  'image/png',
  '.jpg':  'image/jpeg',
  '.ico':  'image/x-icon'
};


function send404(response){
	response.statusCode = 404;
	response.write("Not Found");
	response.end();
}

function send500(response){
	response.statusCode = 500;
	response.write("Server error.");
	response.end();
}

// Render an EJS file as requested
function renderPage(fileName, res, pageName) {
  let filePath = path.join(__dirname, 'views', 'pages', fileName);
  ejs.renderFile(filePath, {products: products, currentPage: pageName}, {}, (err, str) => {
    if (err) {
      console.error("EJS rendering error:", err);
      send500(res);
    } else {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(str);
    }
  });
}

// Render a product EJS file as requested
function renderProductPage(fileName, res, id) {
  let filePath = path.join(__dirname, 'views', 'pages', fileName);

  ejs.renderFile(filePath, {prod: products[id-1], currentPage: 'products'}, {}, (err, str) => {
    if (err) {
      console.error("EJS rendering error:", err);
      send500(res);
    } else {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(str);
    }
  });
}

// Serve static files as requested
function serveStaticFile(req, res) {
  const filePath = path.join(__dirname, req.url);
  const ext = path.extname(filePath);
  const contentType = mimeTypes[ext] || 'application/octet-stream';

  fs.readFile(filePath, (err, data) => {
    if (err) {
      send404(res);
    } else {
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(data);
    }
  });
}

// Handle incoming requests
function requestListener(req, res) {
  let parsedUrl = url.parse(req.url, true); // true parses query string
  let pathName = parsedUrl.pathname;
  let query = parsedUrl.query;

  // Serve static files if the URL matches typical asset folders
  if (pathName.startsWith('/styles/') || pathName.startsWith('/images/') || pathName.startsWith('/icons/') || pathName.startsWith('/scripts/')) {
    serveStaticFile(req, res);
    return;
  }

  // Route EJS pages
  switch (pathName) {
    case '/':
    case '/home':
      renderPage('index.ejs', res, 'home');
      break;
    case '/about':
      renderPage('about.ejs', res, 'about');
      break;
    case '/contact':
      renderPage('contact.ejs', res, 'contact');
      break;
    case '/products':
      renderPage('products.ejs', res, 'products');
      break;
    case '/product':
      if (query.id) {
        renderProductPage('product.ejs', res, query.id);
      }
      else {
        send404(res);
      }
      break;
    default:
      send404(res);
  } 
}

http.createServer(requestListener).listen(PORT);
console.log(`Server running at http://localhost:${PORT}`);
