'use strict';
require('dotenv').config();

const path = require('path');
const express = require('express');
const cookieParser = require('cookie-parser');

const { getAllSettings, categoriesList } = require('./db');
const { attachUser } = require('./middleware/auth');

const pagesRouter = require('./routes/pages');
const authRouter = require('./routes/auth');
const apiRouter = require('./routes/api');
const adminRouter = require('./routes/admin');
const { notifyRouter } = require('./routes/payfast');

const app = express();

app.disable('x-powered-by');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(express.urlencoded({ extended: true, limit: '2mb' }));
app.use(express.json({ limit: '2mb' }));
app.use(cookieParser());

app.use('/public', express.static(path.join(__dirname, 'public'), { maxAge: '7d', index: false }));

const SITE_URL =
  process.env.SITE_URL || `http://localhost:${process.env.PORT || 3000}`;
app.locals.siteUrl = SITE_URL;
const { setSetting } = require('./db');
setSetting('site_url', SITE_URL);

app.use((req, res, next) => {
  const settings = getAllSettings();
  res.locals.site = settings;
  res.locals.categories = categoriesList();
  res.locals.currency = settings.currency || 'ZAR';
  res.locals.currentPath = req.path;
  res.locals.query = req.query;
  next();
});

app.use(attachUser);

app.use('/admin', adminRouter);
app.use('/account', authRouter);
app.use('/api', apiRouter);
app.use('/payfast', notifyRouter);
app.use('/', pagesRouter);

app.use((req, res) => {
  if (req.path.startsWith('/api/')) {
    return res.status(404).json({ error: 'Not found' });
  }
  res.status(404).render('404', { title: 'Page not found' });
});

app.use((err, req, res, next) => {
  console.error(err);
  if (req.path.startsWith('/api/')) {
    return res.status(500).json({ error: 'Something went wrong.' });
  }
  res.status(500).render('500', { title: 'Something went wrong' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`\n  TOUS CINO is running  ->  http://localhost:${PORT}`);
  console.log(`  Admin dashboard        ->  http://localhost:${PORT}/admin`);
  console.log(`  Admin login            ->  http://localhost:${PORT}/admin/login\n`);
});
