require('dotenv').config({
  path: `./env-files/${process.env.NODE_ENV || 'development'}.env`,
});

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const path = require('path');
const expressLayouts = require('express-ejs-layouts');
const cookieParser = require('cookie-parser');
const session = require('express-session');

const initAuthMiddleware = require('./features/login/init-auth-middleware');
const indexRouter = require('./routes/index');
const sessionRouter = require('./routes/session');
const userRouter = require('./routes/user');

const staticFolder = 'public';

const app = express();

//router proxies
app.use('/api', createProxyMiddleware({ target: process.env.backend_url, changeOrigin: true }));
app.use('/uploads', createProxyMiddleware({ target: process.env.backend_url, changeOrigin: true }));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(expressLayouts);

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, staticFolder)));

const { COOKIE_EXPIRATION_MS } = process.env;
app.use(
  session({
    secret: process.env.session_secret,
    name: process.env.SESSION_COOKIE_NAME,
    resave: false,
    saveUninitialized: true,
    cookie: {
      secure: false, //soalnyo harus https
      expires: Date.now() + parseInt(COOKIE_EXPIRATION_MS, 10),
      maxAge: parseInt(COOKIE_EXPIRATION_MS, 10),
    },
  })
);

initAuthMiddleware(app);

// Middleware used for setting error and success messages as available in _ejs_ templates
app.use((req, res, next) => {
  if (req.session) {
    if(req.session.userInfo)req.session.userInfo['name']=req.session.userInfo.username;
    res.locals.messages = req.session.messages;
    res.locals.userInfo = req.session.userInfo;
    req.session.messages = {};
  }
  next();
});

app.use('/', indexRouter);
app.use('/session',sessionRouter);
app.use('/user',userRouter);

// catch 404 and forward to error handler
app.use((req, res) => {
  res.status(404).render('pages/404');
});

module.exports = app;
