/**
 * 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'),
    AsyncResource = require('async_hooks').AsyncResource;

var PgSqlObserver = function (agent) {
    this.agent = agent;
    this.packages = ['pg'];
};

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

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.code || err.name || err.constructor?.name || 'PostgreSQLError';
        var errorMessage = err.message || 'postgresql 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-204', 'Error handling PgSQL error', e, false);
    }
}

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

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

        if (dbc_hash === 0 && connection.connectionParameters) {
            var info = connection.connectionParameters;
            dbc = 'postgresql://';
            dbc += (info.user || '') + '@';
            dbc += (info.host || '') + '/';
            dbc += info.database || '';
            dbc_hash = HashUtil.hashFromString(dbc);
        }

        if (connection.query && !connection.query.__whatap_wrapped__) {
            shimmer.wrap(connection, 'query', createQueryWrapper(agent, dbc));
            connection.query.__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 createQueryWrapper = function(agent, dbcUrl) {
    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 (dbcUrl === 'postgresql://' || !dbc_hash) {
                return original.apply(this, arguments);
            }

            const asyncResource = new AsyncResource('pg-query');
            const callbackResource = new AsyncResource('pg-callback');

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

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

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

                try {
                    if (sql !== null && typeof sql === 'object') {
                        finalSql = sql.text || sql.query || '';
                        params = sql.values || null;
                    } else if (typeof sql === 'string') {
                        finalSql = sql;
                        params = args.length > 1 && Array.isArray(args[1]) ? args[1] : null;
                    }

                    if (typeof finalSql === 'string' && finalSql.length > 0 && params && Array.isArray(params) && params.length > 0) {
                        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('\\' + placeholder + '\\b', 'g'), value);
                        });
                    }
                } catch (formatError) {
                    Logger.printError('WHATAP-205', 'Error formatting PostgreSQL query', formatError, false);
                    if (typeof sql === 'string') {
                        finalSql = sql;
                    } else if (sql && sql.text) {
                        finalSql = sql.text;
                    }
                }

                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-202', 'Processing SQL: ' + finalSql.substring(0, 200), false);
                    } catch (e) {
                        Logger.printError('WHATAP-206', 'PgSqlObserver escapeliteral error', e, false);
                    }
                } else {
                    psql = escapeLiteral(finalSql);
                }

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

                function queryCallback(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.rowCount !== undefined) {
                            resultCount = results.rowCount;
                        } else if (results.rows && Array.isArray(results.rows)) {
                            resultCount = results.rows.length;
                        }
                    }

                    try {
                        TraceSQL.isSlowSQL(currentCtx);
                        if (results && results.command && results.command === 'SELECT' && psql != null && psql.type === 'S') {
                            TraceSQL.isTooManyRecords(resultCount, currentCtx);
                        }
                    } catch (e) {
                        Logger.printError('WHATAP-207', '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('PgSql 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 {
                                queryCallback(callbackArgs[0], callbackArgs[1]);
                            } catch (e) {
                                Logger.printError('WHATAP-208', '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) {
                            queryCallback(null, res);
                            return res;
                        }).catch(function(err) {
                            queryCallback(err, null);
                            throw err;
                        });
                    }

                    return result;
                } catch (queryError) {
                    queryCallback(queryError, null);
                    throw queryError;
                }
            });
        };
    };
};

var wrapPoolConnect = function(agent) {
    return function(original) {
        return function wrappedPoolConnect() {
            var args = Array.prototype.slice.call(arguments);
            var ctx = TraceContextManager.getCurrentContext();

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

            // AsyncResource로 connect 컨텍스트 유지
            const connectionResource = new AsyncResource('pg-pool-connect');
            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 client = callbackArgs[1];

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

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

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

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

                // Promise 기반 처리
                if (result && typeof result.then === 'function' && args.every(arg => typeof arg !== 'function')) {
                    return result.then(connectionResource.bind(function(client) {
                        TraceContextManager.resume(ctx.id);
                        ctx.elapsed = Date.now() - ctx.start_time;

                        if (client && !client.__query_hook__) {
                            client.__query_hook__ = true;
                            hookConnectionMethods(client, agent);
                        }

                        return client;
                    }));
                }

                return result;
            });
        };
    };
};

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

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

    var self = this;

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

                setupDbcInfo(args);

                // if (ctx && !ctx.db_opening) {
                //     ctx.db_opening = true;
                //     ctx.footprint('PgSql Connecting Start');
                //     ctx.start_time = Date.now();
                // }

                var client = new (Function.prototype.bind.apply(original, [null].concat(args)));

                hookConnectionMethods(client, self.agent);

                if (client && client.connect && !client.connect.__whatap_wrapped__) {
                    shimmer.wrap(client, 'connect', function(original) {
                        return function wrappedConnect() {
                            var args = Array.prototype.slice.call(arguments);
                            var ctx = TraceContextManager.getCurrentContext();

                            if (ctx) {
                                ctx.start_time = Date.now();
                                ctx.footprint('PgSql 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);
                                            }

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

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

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

                            // Promise 기반 처리
                            if (result && typeof result.then === 'function') {
                                return result.then(function() {
                                    if (ctx) {
                                        ctx.db_opening = false;
                                        ctx.footprint('PgSql Connecting Done');
                                    }
                                    return result;
                                }).catch(function(err) {
                                    if (ctx) {
                                        ctx.db_opening = false;
                                        ctx.footprint('PgSql Connecting Error');
                                        handleSqlError(ctx, err);
                                    }
                                    throw err;
                                });
                            }

                            return result;
                        };
                    });
                    client.connect.__whatap_wrapped__ = true;
                }

                if (ctx) {
                    ctx.elapsed = Date.now() - ctx.start_time;
                    ctx.footprint('PgSql Client Created');
                    ctx.db_opening = false;
                }

                return client;
            };
        });
        mod.Client.__whatap_wrapped__ = true;
    }

    if (mod.Pool && !mod.Pool.__whatap_wrapped__) {
        shimmer.wrap(mod, 'Pool', function(original) {
            return function wrappedPool() {
                var args = Array.prototype.slice.call(arguments);
                setupDbcInfo(args);

                var pool = new (Function.prototype.bind.apply(original, [null].concat(args)));

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

                    // Pool의 query 메서드 후킹
                    if (pool.query && !pool.query.__whatap_wrapped__) {
                        shimmer.wrap(pool, 'query', createQueryWrapper(self.agent, dbc));
                        pool.query.__whatap_wrapped__ = true;
                    }

                    // Pool의 connect 메서드는 수동 연결 시에만 후킹
                    // pool.query() 내부에서 자동으로 연결을 가져올 때는 후킹하지 않음
                    if (pool.connect && !pool.connect.__whatap_wrapped__) {
                        shimmer.wrap(pool, 'connect', function(original) {
                            return function wrappedConnect() {
                                var args = Array.prototype.slice.call(arguments);
                                var result = original.apply(this, args);

                                // Promise 기반 처리 - 연결 객체에만 후킹 (query는 후킹하지 않음)
                                if (result && typeof result.then === 'function') {
                                    return result.then(function(client) {
                                        // client에는 query 후킹하지 않음 (pool.query()에서 이미 추적됨)
                                        return client;
                                    });
                                } else if (result && typeof result === 'object') {
                                    // 동기적으로 반환된 client에도 query 후킹하지 않음
                                    return result;
                                }

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

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

    if (mod.Client && mod.Client.prototype && mod.Client.prototype.query && !mod.Client.prototype.query.__whatap_wrapped__) {
        shimmer.wrap(mod.Client.prototype, 'query', 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 (dbc_hash === 0 && this.connectionParameters) {
                    var info = this.connectionParameters;
                    dbc = 'postgresql://';
                    dbc += (info.user || '') + '@';
                    dbc += (info.host || '') + '/';
                    dbc += info.database || '';
                    dbc_hash = HashUtil.hashFromString(dbc);
                }

                return createQueryWrapper(self.agent, dbc)(original).apply(this, args);
            };
        });
        mod.Client.prototype.query.__whatap_wrapped__ = true;
    }

    if (mod.Pool && mod.Pool.prototype && mod.Pool.prototype.query && !mod.Pool.prototype.query.__whatap_wrapped__) {
        shimmer.wrap(mod.Pool.prototype, 'query', createQueryWrapper(self.agent, dbc));
        mod.Pool.prototype.query.__whatap_wrapped__ = true;
    }
};

exports.PgSqlObserver = PgSqlObserver;