import express from 'express';
import cookieParser from 'cookie-parser';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';

import { resolveUpload } from './config/api.js';
import { getLayoutData } from './config/layoutCache.js';
import pagesRouter from './routes/pages.js';
import toursRouter from './routes/tours.js';
import blogRouter from './routes/blog.js';
import authRouter from './routes/auth.js';
import seoRouter from './routes/seo.js';

dotenv.config();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
const PORT = process.env.PORT || 4000;

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

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

// Loads site settings + header/footer menus (from a short-TTL cache, not a fresh API call every
// request — see config/layoutCache.js) so partials can render them.
app.use(async (req, res, next) => {
  const layout = await getLayoutData();
  res.locals.site = layout.settings;
  res.locals.headerMenus = layout.headerMenus;
  res.locals.footerMenus = layout.footerMenus;
  res.locals.resolveUpload = resolveUpload;
  res.locals.currentPath = req.path;
  res.locals.customer = req.cookies.rmt_customer ? JSON.parse(req.cookies.rmt_customer) : null;
  next();
});

app.use('/', seoRouter);
app.use('/', pagesRouter);
app.use('/tours', toursRouter);
app.use('/blog', blogRouter);
app.use('/', authRouter);

app.use((req, res) => {
  res.status(404).render('pages/404', { title: 'Page Not Found' });
});

app.listen(PORT, () => {
  console.log(`RouteMate public website running on port ${PORT}`);
});
