"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var ErrorMapperService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ErrorMapperService = void 0;
const common_1 = require("@nestjs/common");
const solid_registry_1 = require("./solid-registry");
let ErrorMapperService = ErrorMapperService_1 = class ErrorMapperService {
    constructor(solidRegistry) {
        this.solidRegistry = solidRegistry;
        this.logger = new common_1.Logger(ErrorMapperService_1.name);
    }
    mapException(exc) {
        const combined = this.combineErrorText(exc);
        return this.matchCode(combined);
    }
    mapMessage(message, trace) {
        const combined = `${message ?? ''}\n${trace ?? ''}`.toLowerCase();
        return this.matchCode(combined);
    }
    getMessage(code) {
        const meta = this.lookupMeta(code);
        return (meta ?? { message: 'An unexpected error occurred.' }).message;
    }
    getHttpStatus(code) {
        const meta = this.lookupMeta(code);
        return meta?.httpStatus ?? 500;
    }
    matchCode(combined) {
        const rules = this.getAllRulesSorted();
        for (const rule of rules) {
            try {
                if (rule.match(combined))
                    return rule.code;
            }
            catch (e) {
                this.logger.warn(`Error rule threw in match(): code=${rule.code} provider? — ${e}`);
            }
        }
        return 'solidx-unknown-error';
    }
    lookupMeta(code) {
        const rules = this.getAllRulesSorted();
        const rule = rules.find((r) => r.code === code);
        if (rule?.meta)
            return rule.meta;
        const providers = this.getProviders();
        for (const p of providers) {
            if (p.resolve) {
                const meta = p.resolve(code);
                if (meta)
                    return meta;
            }
        }
        return undefined;
    }
    getAllRulesSorted() {
        const providers = this.getProviders();
        const all = [];
        for (const p of providers) {
            try {
                const rules = p.rules() ?? [];
                all.push(...rules);
            }
            catch (e) {
                this.logger.warn(`ErrorCodeProvider.rules() failed for ${p.name?.()}: ${e}`);
            }
        }
        return all.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
    }
    getProviders() {
        return this.solidRegistry
            .getErrorCodeProviders()
            .map((w) => w.instance)
            .filter(Boolean);
    }
    combineErrorText(exc) {
        if (typeof exc === 'string')
            return exc.toLowerCase();
        if (exc instanceof Error) {
            const message = exc.message ?? '';
            const stack = exc.stack ?? '';
            return `${message}\n${stack}`.toLowerCase();
        }
        if (exc && typeof exc === 'object') {
            try {
                const obj = exc;
                const msg = String(obj.message ?? obj['Message'] ?? '');
                const name = String(obj.name ?? obj['__type'] ?? '');
                const stack = String(obj.stack ?? '');
                const json = this.safeJsonStringify(obj);
                return `${name}\n${msg}\n${stack}\n${json}`.toLowerCase();
            }
            catch {
            }
        }
        return String(exc ?? '').toLowerCase();
    }
    safeJsonStringify(obj) {
        try {
            return JSON.stringify(obj);
        }
        catch {
            return '';
        }
    }
};
exports.ErrorMapperService = ErrorMapperService;
exports.ErrorMapperService = ErrorMapperService = ErrorMapperService_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [solid_registry_1.SolidRegistry])
], ErrorMapperService);
//# sourceMappingURL=error-mapper.service.js.map