const MODULE_NAME = 'SDK-SUPPLIER-PRODUCT-QUOTA.CONTROL-PANEL';

const path = require('path');
const express = require('express');
const nunjucks = require('nunjucks');
const session = require('express-session');
const uniqid = require('uniqid');

const config = require('komodo-sdk/config');
const logger = require('tektrans-logger');

const routerMain = require('./routers/main');
const coreTerminalAuth = require('../core-terminal-auth');

const app = express();

app.use(session({
    secret: (config.sdk_supplier_product_quota
            && config.sdk_supplier_product_quota.session_secret) || uniqid(),
    resave: true,
    saveUninitialized: false,
}));

const viewsDir = path.join(__dirname, 'views');
nunjucks.configure(viewsDir, {
    autoescape: true,
    express: app,
    noCache: config.sdk_supplier_product_quota && config.sdk_supplier_product_quota.no_cache,
});

const staticDir = path.join(__dirname, '../../static');
app.use(express.static(staticDir));
logger.info(`${MODULE_NAME}: Serving static files on ${staticDir}`);

function validateSession(req, res, next) {
    if (!req.session.terminal || !req.session.terminal.id) {
        res.redirect('/login');
        return;
    }

    next();
}

app.use((req, res, next) => {
    res.locals.handler_name = config.handler_name;
    res.locals.xid = uniqid();
    next();
});

app.get('/', (req, res) => {
    res.redirect('/main');
});

app.get('/logout', (req, res) => {
    req.session.terminal = null;
    req.session.store = null;

    res.redirect('/login');
});

app.get('/login', (req, res) => {
    res.render('signin.njk');
});

app.post('/login', express.urlencoded({ extended: false }), async (req, res) => {
    const { username, password } = req.body;
    const terminal = await coreTerminalAuth.validateWebPassword(username, password);

    if (!terminal || !terminal.store_is_super) {
        res.redirect('/login');
        return;
    }

    if (
        config.sdk_supplier_product_quota
        && !config.sdk_supplier_product_quota.allow_non_super_terminal_login
        && !terminal.terminal_is_super
    ) {
        res.redirect('/login');
        return;
    }

    req.session.terminal = {
        id: terminal.id,
        name: terminal.name,
        super: terminal.terminal_is_super,
    };

    req.session.store = {
        id: terminal.store_id,
        name: terminal.store_name,
        super: terminal.store_is_super,
    };

    res.redirect('/');
});

app.use('/main', validateSession, routerMain);

const listenPort = config.sdk_supplier_product_quota && config.sdk_supplier_product_quota.port;
if (listenPort) {
    app.listen(listenPort, () => {
        logger.info(`4226C307 ${MODULE_NAME}: Control panel ready`, { listenPort });
    }).on('error', (err) => {
        logger.warn(`83FB2789 ${MODULE_NAME}: Control panel failed to start`, {
            listenPort, eCode: err.code, eMessage: err.message,
        });
    });
}
