/**
 * Copyright 2023 the WHATAP project authors. All rights reserved.
 * Use of this source code is governed by a license that
 * can be found in the LICENSE file.
 */

var TraceContextManager = require('../trace/trace-context-manager'),
    ParsedSql = require('../trace/parsed-sql'),
    conf = require('../conf/configure'),
    IntKeyMap = require('../util/intkey-map'),
    EscapeLiteralSQL = require('../util/escape-literal-sql'),
    HashUtil = require('../util/hashutil'),
    Logger = require('../logger'),
    DateUtil = require('../util/dateutil'),
    AsyncSender = require('../udp/async_sender'),
    PacketTypeEnum = require('../udp/packet_type_enum'),
    shimmer = require('../core/shimmer'),
    TraceSQL = require('../trace/trace-sql'),
    AsyncResource = require('async_hooks').AsyncResource;

var OracleObserver = function (agent) {
    this.agent = agent;
    this.packages = ['oracledb'];
};

var dbc_hash = 0;
var dbc = 'oracle://';

var hookedInstances = new WeakSet();

var checkedSql = new IntKeyMap(2000).setMax(2000);
var nonLiteSql = new IntKeyMap(5000).setMax(5000);
var date = DateUtil.yyyymmdd();

function handleSqlError(ctx, err) {
    if (!err) return;

    try {
        var errorClass = err.errorNum || err.code || err.name || err.constructor?.name || 'OracleError';
        var errorMessage = err.message || 'oracle error';
        var errorStack = '';

        if (conf.trace_sql_error_stack && conf.trace_sql_error_depth && err.stack) {
            var traceDepth = conf.trace_sql_error_depth;
            var stackLines = err.stack.split("\n");
            if (stackLines.length > traceDepth) {
                stackLines = stackLines.slice(0, traceDepth + 1);
            }
            errorStack = stackLines.join("\n");
        }

        var shouldAddError = false;
        if (conf._is_trace_ignore_err_cls_contains === true && errorClass &&
            errorClass.toString().indexOf(conf.trace_ignore_err_cls_contains) < 0) {
            shouldAddError = true;
        } else if (conf._is_trace_ignore_err_msg_contains === true && errorMessage &&
            errorMessage.indexOf(conf.trace_ignore_err_msg_contains) < 0) {
            shouldAddError = true;
        } else if (conf._is_trace_ignore_err_cls_contains === false &&
            conf._is_trace_ignore_err_msg_contains === false) {
            shouldAddError = true;
        }

        if (shouldAddError) {
            if (!ctx.error) ctx.error = 1;
            ctx.status = 500;
            var errors = [errorClass];
            if (errorMessage) {
                errors.push(errorMessage);
            }
            if (errorStack || err.stack) {
                errors.push(errorStack || err.stack);
            }

            AsyncSender.send_packet(PacketTypeEnum.TX_ERROR, ctx, errors);
        }
    } catch (e) {
        Logger.printError('WHATAP-251', 'Error handling Oracle error', e, false);
    }
}

function setupDbcInfo(connectionInfo) {
    if (dbc_hash === 0 && connectionInfo) {
        var connectInfo = connectionInfo.connectString || connectionInfo.connectionString || '';
        var user = connectionInfo.user || '';
        dbc = 'oracle://' + user + '@' + connectInfo;
        dbc_hash = HashUtil.hashFromString(dbc);
    }
}

function hookConnectionMethods(connection, agent) {
    if (connection && !hookedInstances.has(connection)) {
        hookedInstances.add(connection);
        // Logger.print('WHATAP-ORACLE-CONNECTION', 'Hooking new Oracle connection object', false);

        if (connection.execute && !connection.execute.__whatap_wrapped__) {
            shimmer.wrap(connection, 'execute', createExecuteWrapper(agent, dbc));
            connection.execute.__whatap_wrapped__ = true;
        }
    }
}

function escapeLiteral(sql) {
    if (sql == null) {
        sql = '';
    }

    if (date !== DateUtil.yyyymmdd()) {
        checkedSql.clear();
        nonLiteSql.clear();
        date = DateUtil.yyyymmdd();
    }

    var sqlHash = HashUtil.hashFromString(sql);
    var psql = nonLiteSql.get(sqlHash);

    if (psql != null) {
        return psql;
    }
    psql = checkedSql.get(sqlHash);

    if (psql != null) {
        return psql;
    }

    var els = new EscapeLiteralSQL(sql);
    els.process();

    var hash = HashUtil.hashFromString(els.getParsedSql());

    if (hash === sqlHash) {
        psql = new ParsedSql(els.sqlType, hash, null);
        nonLiteSql.put(sqlHash, psql);
    } else {
        psql = new ParsedSql(els.sqlType, hash, els.getParameter());
        checkedSql.put(sqlHash, psql);
    }
    return psql;
}

var createExecuteWrapper = function(agent, dbcUrl) {
    return function(original) {
        return function wrappedExecute() {
            var args = Array.prototype.slice.call(arguments);
            var ctx = TraceContextManager.getCurrentContext();

            if (ctx == null || args[0] == null) {
                return original.apply(this, arguments);
            }

            if (dbcUrl === 'oracle://' || !dbc_hash) {
                return original.apply(this, arguments);
            }

            const asyncResource = new AsyncResource('oracle-execute');
            const callbackResource = new AsyncResource('oracle-callback');

            return asyncResource.runInAsyncScope(() => {
                ctx.start_time = Date.now();
                ctx.elapsed = 0;
                AsyncSender.send_packet(PacketTypeEnum.TX_DB_CONN, ctx, [dbcUrl]);

                var sql_start_time = Date.now();
                ctx.footprint('Oracle Query Start');
                ctx.sql_count++;

                var sql = args.length > 0 ? args[0] : undefined;
                var params = args.length > 1 ? args[1] : null;
                var finalSql = '';

                try {
                    if (typeof sql === 'string') {
                        finalSql = sql;

                        // Oracle 파라미터 치환 (:name 형태)
                        if (params && typeof params === 'object') {
                            if (Array.isArray(params)) {
                                // 배열 형태 파라미터 [value1, value2, ...]
                                params.forEach((param, index) => {
                                    const placeholder = ':' + (index + 1);
                                    const value = param === null ? 'NULL' :
                                        typeof param === 'string' ? `'${param.replace(/'/g, "''")}'` :
                                            String(param);
                                    finalSql = finalSql.replace(new RegExp(':' + (index + 1) + '\\b', 'g'), value);
                                });
                            } else {
                                // 객체 형태 파라미터 {name: value, id: value}
                                Object.keys(params).forEach(key => {
                                    const placeholder = ':' + key;
                                    const value = params[key] === null ? 'NULL' :
                                        typeof params[key] === 'string' ? `'${params[key].replace(/'/g, "''")}'` :
                                            String(params[key]);
                                    finalSql = finalSql.replace(new RegExp(':' + key + '\\b', 'g'), value);
                                });
                            }
                        }
                    }
                } catch (formatError) {
                    Logger.printError('WHATAP-ORACLE-FORMAT', 'Error formatting Oracle query', formatError, false);
                    if (typeof sql === 'string') {
                        finalSql = sql;
                    }
                }

                if (typeof finalSql !== 'string' || finalSql.length === 0) {
                    finalSql = '';
                }

                var psql = null;
                if (typeof finalSql === 'string' && finalSql.length > 0) {
                    try {
                        psql = escapeLiteral(finalSql);
                        // Logger.print('WHATAP-SQL-DEBUG', 'Processing SQL: ' + finalSql.substring(0, 200), false);
                    } catch (e) {
                        Logger.printError('WHATAP-252', 'OracleObserver escapeliteral error', e, false);
                    }
                } else {
                    psql = escapeLiteral(finalSql);
                }

                ctx.active_sqlhash = true;
                ctx.active_dbc = dbc_hash;

                function executeCallback(err, results) {
                    var currentCtx = TraceContextManager.getCurrentContext();
                    if (currentCtx == null) {
                        return;
                    }

                    TraceContextManager.resume(currentCtx.id);

                    var sql_elapsed = Date.now() - sql_start_time;
                    var resultCount = 0;

                    if (err) {
                        handleSqlError(currentCtx, err);
                    }

                    if (!err && results) {
                        if (results.rows && Array.isArray(results.rows)) {
                            resultCount = results.rows.length;
                        } else if (results.rowsAffected !== undefined) {
                            resultCount = results.rowsAffected;
                        }
                    }

                    try {
                        TraceSQL.isSlowSQL(currentCtx);
                        if (!err && results && results.rows && Array.isArray(results.rows) && psql != null && psql.type === 'S') {
                            TraceSQL.isTooManyRecords(resultCount, currentCtx);
                        }
                    } catch (e) {
                        Logger.printError('WHATAP-TRACESQL', 'Error in TraceSQL processing', e, false);
                    }

                    currentCtx.elapsed = sql_elapsed;
                    currentCtx.active_sqlhash = false;
                    AsyncSender.send_packet(PacketTypeEnum.TX_SQL, currentCtx, [dbcUrl, finalSql, String(resultCount)]);

                    currentCtx.footprint('Oracle Query Done');
                }

                var callbackWrapped = false;
                var hasCallback = false;

                // 콜백 찾기 및 래핑
                for (var i = args.length - 1; i >= 0; i--) {
                    if (typeof args[i] === 'function') {
                        hasCallback = true;
                        var originalCallback = args[i];
                        args[i] = callbackResource.bind(function() {
                            var callbackArgs = Array.prototype.slice.call(arguments);
                            try {
                                executeCallback(callbackArgs[0], callbackArgs[1]);
                            } catch (e) {
                                Logger.printError('WHATAP-CALLBACK', 'Error in callback hook', e, false);
                            }
                            if (originalCallback && typeof originalCallback === 'function') {
                                return originalCallback.apply(this, callbackArgs);
                            }
                        });
                        callbackWrapped = true;
                        break;
                    }
                }

                try {
                    const result = original.apply(this, args);

                    // Promise 기반 처리
                    if (!hasCallback && result && typeof result.then === 'function') {
                        return result.then(function(res) {
                            executeCallback(null, res);
                            return res;
                        }).catch(function(err) {
                            executeCallback(err, null);
                            throw err;
                        });
                    }

                    return result;
                } catch (executeError) {
                    executeCallback(executeError, null);
                    throw executeError;
                }
            });
        };
    };
};

OracleObserver.prototype.inject = function (mod, moduleName) {
    if (mod.__whatap_observe__) {
        return;
    }
    mod.__whatap_observe__ = true;
    Logger.initPrint("OracleObserver");

    if (conf.sql_enabled === false) {
        return;
    }

    var self = this;

    // getConnection 래핑
    if (mod.getConnection && !mod.getConnection.__whatap_wrapped__) {
        shimmer.wrap(mod, 'getConnection', function(original) {
            return function wrappedGetConnection() {
                var args = Array.prototype.slice.call(arguments);
                var connectionInfo = args[0] || {};
                var ctx = TraceContextManager.getCurrentContext();

                setupDbcInfo(connectionInfo);

                if (ctx == null) {
                    return original.apply(this, arguments);
                }

                const connectionResource = new AsyncResource('oracle-getconnection');

                return connectionResource.runInAsyncScope(() => {
                    ctx.start_time = Date.now();
                    ctx.footprint('Oracle Connecting Start');
                    ctx.db_opening = true;

                    // 콜백 래핑
                    for (var i = args.length - 1; i >= 0; i--) {
                        if (typeof args[i] === 'function') {
                            var originalCallback = args[i];
                            args[i] = connectionResource.bind(function() {
                                var callbackArgs = Array.prototype.slice.call(arguments);
                                var err = callbackArgs[0];
                                var connection = callbackArgs[1];

                                if (ctx) {
                                    TraceContextManager.resume(ctx.id);
                                    ctx.elapsed = Date.now() - ctx.start_time;
                                    ctx.db_opening = false;

                                    if (err) {
                                        handleSqlError(ctx, err);
                                        ctx.footprint('Oracle Connecting Error');
                                    } else {
                                        ctx.footprint('Oracle Connecting Done');
                                    }
                                }

                                if (connection) {
                                    hookConnectionMethods(connection, self.agent);
                                }

                                return originalCallback.apply(this, callbackArgs);
                            });
                            break;
                        }
                    }

                    var result = original.apply(this, args);

                    // Promise 기반 처리
                    if (result && typeof result.then === 'function') {
                        return result.then(connectionResource.bind(function(connection) {
                            if (ctx) {
                                TraceContextManager.resume(ctx.id);
                                ctx.elapsed = Date.now() - ctx.start_time;
                                ctx.db_opening = false;
                                ctx.footprint('Oracle Connecting Done');
                            }

                            if (connection) {
                                hookConnectionMethods(connection, self.agent);
                            }

                            return connection;
                        })).catch(connectionResource.bind(function(err) {
                            if (ctx) {
                                TraceContextManager.resume(ctx.id);
                                ctx.elapsed = Date.now() - ctx.start_time;
                                ctx.db_opening = false;
                                ctx.footprint('Oracle Connecting Error');
                                handleSqlError(ctx, err);
                            }
                            throw err;
                        }));
                    }
                    return result;
                });
            };
        });
        mod.getConnection.__whatap_wrapped__ = true;
    }

    // createPool 래핑
    if (mod.createPool && !mod.createPool.__whatap_wrapped__) {
        shimmer.wrap(mod, 'createPool', function(original) {
            return function wrappedCreatePool() {
                var args = Array.prototype.slice.call(arguments);
                var poolAttrs = args[0] || {};

                setupDbcInfo(poolAttrs);

                var result = original.apply(this, args);

                // 콜백 방식 처리
                if (args.length > 0 && typeof args[args.length - 1] === 'function') {
                    return result;
                }

                // Promise 방식 처리
                if (result && typeof result.then === 'function') {
                    return result.then(function(pool) {
                        if (pool && !hookedInstances.has(pool)) {
                            hookedInstances.add(pool);

                            if (pool.getConnection && !pool.getConnection.__whatap_wrapped__) {
                                shimmer.wrap(pool, 'getConnection', function(originalGetConn) {
                                    return function wrappedPoolGetConnection() {
                                        var args = Array.prototype.slice.call(arguments);
                                        var ctx = TraceContextManager.getCurrentContext();

                                        if (ctx == null) {
                                            return originalGetConn.apply(this, arguments);
                                        }

                                        const poolConnectionResource = new AsyncResource('oracle-pool-getconnection');

                                        return poolConnectionResource.runInAsyncScope(() => {
                                            ctx.start_time = Date.now();
                                            ctx.footprint('Oracle Pool Connection Start');
                                            ctx.db_opening = true;

                                            var result = originalGetConn.apply(this, args);

                                            // Promise 기반 처리
                                            if (result && typeof result.then === 'function') {
                                                return result.then(poolConnectionResource.bind(function(connection) {
                                                    if (ctx) {
                                                        TraceContextManager.resume(ctx.id);
                                                        ctx.elapsed = Date.now() - ctx.start_time;
                                                        ctx.db_opening = false;
                                                        ctx.footprint('Oracle Pool Connection Done');
                                                    }

                                                    if (connection) {
                                                        hookConnectionMethods(connection, self.agent);
                                                    }

                                                    return connection;
                                                })).catch(poolConnectionResource.bind(function(err) {
                                                    if (ctx) {
                                                        TraceContextManager.resume(ctx.id);
                                                        ctx.elapsed = Date.now() - ctx.start_time;
                                                        ctx.db_opening = false;
                                                        ctx.footprint('Oracle Pool Connection Error');
                                                        handleSqlError(ctx, err);
                                                    }
                                                    throw err;
                                                }));
                                            }

                                            return result;
                                        });
                                    };
                                });
                                pool.getConnection.__whatap_wrapped__ = true;
                            }
                        }
                        return pool;
                    });
                }

                return result;
            };
        });
        mod.createPool.__whatap_wrapped__ = true;
    }
};

exports.OracleObserver = OracleObserver;