/**
 * Copyright 2016 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');
const { AsyncResource } = require('async_hooks');

var MysqlObserver = function (agent) {
    this.agent = agent;
    this.packages = ['mysql'];
};

// 전역 dbc 정보
var dbc_hash = 0;
var dbc = 'mysql://';

// 후킹된 객체 추적
var hookedInstances = new WeakSet();

// 공통 함수들
function handleSqlError(ctx, err, sqlHash) {
    if (!err) return;

    try {
        var errorClass = err.code || err.name || err.constructor?.name || 'MySQLError';
        var errorMessage = err.message || err.sqlMessage || 'mysql 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.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-232', 'Error handling MySQL error', e, false);
    }
}

function handleProtocolError(ctx, error) {
    if (!error) return;

    try {
        var errorClass = error.code || error.name || error.constructor?.name || 'MySQLError';
        var errorMessage = error.message || 'mysql error';

        var shouldAddError = false;
        if (conf._is_trace_ignore_err_cls_contains === true && errorClass.indexOf(conf.trace_ignore_err_cls_contains) < 0) {
            shouldAddError = true;
        } else if (conf._is_trace_ignore_err_msg_contains === true && 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) {
            ctx.error = 1;
            ctx.status = 500;
            var errors = [errorClass];
            if (errorMessage) {
                errors.push(errorMessage);
            }
            if (error.stack) {
                errors.push(error.stack);
            }

            AsyncSender.send_packet(PacketTypeEnum.TX_ERROR, ctx, errors);
        }
    } catch (e) {
        Logger.printError('WHATAP-PROTOCOL-ERROR-HANDLING', 'Error processing protocol error', e, false);
    }
}

function setupDbcInfo(args) {
    if (dbc_hash === 0 && args.length > 0) {
        var info = args[0] || {};
        dbc = 'mysql://';
        dbc += info.user || '';
        dbc += "@";
        dbc += info.host || '';
        dbc += '/';
        dbc += info.database || '';
        dbc_hash = HashUtil.hashFromString(dbc);
    }
}

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

        // query와 execute 메서드 후킹
        if (connection.query && !connection.query.__whatap_wrapped__) {
            shimmer.wrap(connection, 'query', createQueryWrapper(agent, dbc, mysqlModule));
            connection.query.__whatap_wrapped__ = true;
        }
        if (connection.execute && !connection.execute.__whatap_wrapped__) {
            shimmer.wrap(connection, 'execute', createQueryWrapper(agent, dbc, mysqlModule));
            connection.execute.__whatap_wrapped__ = true;
        }

        // 프로토콜 에러 델리게이트 래핑
        if (connection._protocol && connection._protocol._delegateError &&
            !connection._protocol._delegateError.__whatap_wrapped__) {
            try {
                shimmer.wrap(connection._protocol, '_delegateError', function(original) {
                    return function wrappedDelegateError() {
                        var args = Array.prototype.slice.call(arguments);
                        var ctx = TraceContextManager.getCurrentContext();

                        if (ctx && args[0]) {
                            handleSqlError(ctx, args[0], 0);
                        }

                        return original.apply(this, args);
                    };
                });
                connection._protocol._delegateError.__whatap_wrapped__ = true;
            } catch (e) {
                Logger.printError('WHATAP-PROTOCOL-HOOK', 'Error hooking _delegateError', e, false);
            }
        }
    }
}

// 쿼리 래핑 함수
var createQueryWrapper = function(agent, dbcUrl, mysqlModule) {
    return function(original) {
        return function wrappedQuery() {
            var args = Array.prototype.slice.call(arguments);
            var ctx = TraceContextManager.getCurrentContext();

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

            if (args[0].sql == null && typeof args[0] != 'string') {
                return original.apply(this, arguments);
            }

            // AsyncResource 생성
            const asyncResource = new AsyncResource('mysql-query');
            const callbackResource = new AsyncResource('mysql-callback');

            return asyncResource.runInAsyncScope(() => {
                ctx.start_time = Date.now();

                // DB 연결 패킷 전송 (elapsed = 0으로 설정)
                ctx.elapsed = 0;
                AsyncSender.send_packet(PacketTypeEnum.TX_DB_CONN, ctx, [dbcUrl]);

                // SQL 시작 시간 기록
                var sql_start_time = Date.now();
                ctx.footprint('MySql Query Start');

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

                // mysql.format()을 사용하여 최종 SQL 구성
                try {
                    if (typeof sql === 'string') {
                        // 일반 문자열 쿼리인 경우
                        if (values && typeof mysqlModule.format === 'function') {
                            finalSql = mysqlModule.format(sql, values);
                        } else {
                            finalSql = sql;
                        }
                    } else if (sql && typeof sql === 'object') {
                        // 쿼리 객체인 경우 (prepared statement 등)
                        if (sql.sql) {
                            if (sql.values && typeof mysqlModule.format === 'function') {
                                finalSql = mysqlModule.format(sql.sql, sql.values);
                            } else {
                                finalSql = sql.sql;
                            }
                        }
                    }
                } catch (formatError) {
                    Logger.printError('WHATAP-SQL-FORMAT', 'Error formatting SQL with mysql.format()', formatError, false);
                    // 포맷 실패 시 원본 사용
                    if (typeof sql === 'string') {
                        finalSql = sql;
                    } else if (sql && sql.sql) {
                        finalSql = sql.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-233', 'MysqlObserver escapeliteral error', e, false);
                    }
                } else {
                    psql = escapeLiteral(finalSql);
                }

                var sqlHash = psql ? psql.sql : 0;
                ctx.active_sqlhash = true;

                // 쿼리 콜백 처리 함수 - AsyncResource로 바인딩
                function queryCallback(err, results) {
                    // AsyncResource 스코프 내에서 실행되므로 컨텍스트 유지됨
                    var ctx = TraceContextManager.getCurrentContext();
                    if (ctx == null) {
                        return;
                    }

                    TraceContextManager.resume(ctx.id);

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

                    // 에러 처리 먼저 수행 (TX_ERROR 패킷 전송)
                    if (err) {
                        handleSqlError(ctx, err, sqlHash);
                    }

                    // 결과 개수 계산
                    if (!err && results) {
                        if (Array.isArray(results)) {
                            resultCount = results.length;
                        } else if (results.affectedRows !== undefined) {
                            resultCount = results.affectedRows;
                        } else if (results.changedRows !== undefined) {
                            resultCount = results.changedRows;
                        }
                    }

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

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

                    ctx.footprint('MySql Query Done');
                }

                var callbackWrapped = false;

                // 일반 콜백 래핑 - callbackResource로 바인딩
                for (var i = args.length - 1; i >= 0; i--) {
                    if (typeof args[i] === 'function') {
                        var originalCallback = args[i];
                        // AsyncResource로 콜백 바인딩
                        args[i] = callbackResource.bind(function() {
                            var callbackArgs = Array.prototype.slice.call(arguments);
                            try {
                                queryCallback(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;
                    }
                }

                // _callback 래핑 - callbackResource로 바인딩
                if (!callbackWrapped && args.length > 0 && args[0]._callback) {
                    try {
                        var originalCallback = args[0]._callback;
                        args[0]._callback = callbackResource.bind(function() {
                            var callbackArgs = Array.prototype.slice.call(arguments);
                            try {
                                queryCallback(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;
                    } catch (e) {
                        Logger.printError('WHATAP-CALLBACK-HOOK', 'Error hooking _callback', e, false);
                    }
                }

                try {
                    return original.apply(this, args);
                } catch (queryError) {
                    queryCallback(queryError, null);
                    throw queryError;
                }
            });
        };
    };
};

// getConnection 래핑 함수
var wrapGetConnection = function(agent, mysqlModule) {
    return function(original) {
        return function wrappedGetConnection() {
            var args = Array.prototype.slice.call(arguments);
            var ctx = TraceContextManager.getCurrentContext();

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

            // AsyncResource로 getConnection 컨텍스트 유지
            const connectionResource = new AsyncResource('mysql-getConnection');

            return connectionResource.runInAsyncScope(() => {
                ctx.start_time = Date.now();

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

                            TraceContextManager.resume(ctx.id);
                            ctx.elapsed = Date.now() - ctx.start_time;

                            if (!err && conn && !conn.__query_hook__) {
                                conn.__query_hook__ = true;
                                hookConnectionMethods(conn, agent, mysqlModule);
                            }

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

                return original.apply(this, args);
            });
        };
    };
};

// 유틸리티 함수들
var checkedSql = new IntKeyMap(2000).setMax(2000);
var nonLiteSql = new IntKeyMap(5000).setMax(5000);
var date = DateUtil.yyyymmdd();

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

    if (date !== DateUtil.yyyymmdd()) {
        checkedSql.clear();
        nonLiteSql.clear();
        date = DateUtil.yyyymmdd();
        Logger.print('WHATAP-SQL-CLEAR', 'MysqlObserver CLEAR OK!!!!!!!!!!!!!!!!', false);
    }

    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;
}

// 메인 inject 함수
MysqlObserver.prototype.inject = function (mod, moduleName) {
    if (mod.__whatap_observe__) {
        return;
    }
    mod.__whatap_observe__ = true;
    Logger.initPrint("MysqlObserver");

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

    var self = this;

    // createConnection 래핑
    if (mod.createConnection && !mod.createConnection.__whatap_wrapped__) {
        shimmer.wrap(mod, 'createConnection', function(original) {
            return function wrappedCreateConnection() {
                var args = Array.prototype.slice.call(arguments);
                var ctx = TraceContextManager.getCurrentContext();

                setupDbcInfo(args);

                if (ctx) {
                    ctx.db_opening = true;
                    ctx.footprint('MySql Connecting Start');
                    ctx.start_time = Date.now();
                }

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

                // 연결 객체 후킹
                hookConnectionMethods(result, self.agent, mod);

                // connect 메서드 래핑
                if (result && result.connect && !result.connect.__whatap_wrapped__) {
                    shimmer.wrap(result, 'connect', function(original) {
                        return function wrappedConnect() {
                            var args = Array.prototype.slice.call(arguments);
                            var ctx = TraceContextManager.getCurrentContext();

                            if (ctx) {
                                ctx.footprint('MySql 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] = function() {
                                            var callbackArgs = Array.prototype.slice.call(arguments);
                                            var err = callbackArgs[0];

                                            if (err) {
                                                handleSqlError(ctx, err, 0);
                                            }

                                            ctx.db_opening = false;
                                            ctx.footprint('MySql Connecting Done');
                                            TraceContextManager.resume(ctx.id);

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

                            return original.apply(this, args);
                        };
                    });
                    result.connect.__whatap_wrapped__ = true;
                }

                if (ctx) {
                    ctx.elapsed = Date.now() - ctx.start_time;
                    ctx.footprint('MySql Connecting Done');
                    ctx.db_opening = false;
                }

                return result;
            };
        });
        mod.createConnection.__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);
                setupDbcInfo(args);

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

                if (pool && !hookedInstances.has(pool)) {
                    hookedInstances.add(pool);

                    if (pool.getConnection && !pool.getConnection.__whatap_wrapped__) {
                        shimmer.wrap(pool, 'getConnection', wrapGetConnection(self.agent, mod));
                        pool.getConnection.__whatap_wrapped__ = true;
                    }
                }

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

    // createPoolCluster 래핑
    if (mod.createPoolCluster && !mod.createPoolCluster.__whatap_wrapped__) {
        shimmer.wrap(mod, 'createPoolCluster', function(original) {
            return function wrappedCreatePoolCluster() {
                var args = Array.prototype.slice.call(arguments);
                setupDbcInfo(args);

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

                if (poolCluster && !hookedInstances.has(poolCluster)) {
                    hookedInstances.add(poolCluster);

                    if (poolCluster.getConnection && !poolCluster.getConnection.__whatap_wrapped__) {
                        shimmer.wrap(poolCluster, 'getConnection', wrapGetConnection(self.agent, mod));
                        poolCluster.getConnection.__whatap_wrapped__ = true;
                    }
                }

                return poolCluster;
            };
        });
        mod.createPoolCluster.__whatap_wrapped__ = true;
    }
};

exports.MysqlObserver = MysqlObserver;