const MODULE_NAME = 'SPQ.CORE-TERMINAL-AUTH';

const axios = require('axios').default;

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

const validateWebPassword = async (terminalName, webPassword, xid) => {
    const params = {
        terminal_name: terminalName,
        web_password: webPassword,
        request_by: config.handler_name,
    };

    let result;
    const endpoint = `${coreUrl}/services/terminalAuthentication`;
    try {
        logger.verbose(`${MODULE_NAME}: Requesting CORE to validate terminal web password`, { xid, endpoint, terminalName });
        result = await axios.post(endpoint, params);
    } catch (e) {
        logger.warn(`${MODULE_NAME}: Exception on requesting to CORE in validating terminal credential`, {
            xid, endpoint, terminalName, eCode: e.code, eMessage: e.message,
        });

        return false;
    }

    if (!result || !result.data) {
        logger.warn(`${MODULE_NAME}: Empty or invalid CORE response`, {
            xid, body: result && result.data,
        });
        return false;
    }

    return result.data.terminal;
};
exports.validateWebPassword = validateWebPassword;
