// SPDX-License-Identifier: Apache-2.0
import { ConfigKeyFormatter } from '../../key/config-key-formatter.js';
import { IllegalArgumentError } from '../../../business/errors/illegal-argument-error.js';
import { ObjectMappingError } from '../api/object-mapping-error.js';
export class FlatKeyMapper {
    formatter;
    constructor(formatter = ConfigKeyFormatter.instance()) {
        this.formatter = formatter;
        if (!formatter) {
            throw new IllegalArgumentError('formatter must be provided');
        }
    }
    flatten(data) {
        const fkm = new Map();
        for (const [key, value] of Object.entries(data)) {
            this.flattenKVPair(fkm, key, value);
        }
        return fkm;
    }
    flattenKVPair(fkm, key, value) {
        // If the value is null or undefined, we don't need to do anything since the key should not be added to the map.
        if (value === null || value === undefined) {
            return;
        }
        const valueType = typeof value;
        switch (valueType) {
            case 'string':
            case 'number':
            case 'boolean':
            case 'bigint': {
                fkm.set(this.formatter.normalize(key), value.toString());
                break;
            }
            case 'object': {
                if (Array.isArray(value)) {
                    this.flattenArray(fkm, key, value);
                }
                else {
                    this.flattenObject(fkm, key, value);
                }
                break;
            }
            default: {
                throw new ObjectMappingError(`Unsupported value type [ key = '${key}', value = '${value}', type = '${valueType}' ]`);
            }
        }
    }
    flattenArray(fkm, key, value) {
        for (const [index, element] of value.entries()) {
            const arrayKey = this.formatter.join(key, index.toString());
            this.flattenKVPair(fkm, arrayKey, element);
        }
    }
    flattenObject(fkm, key, value) {
        for (const [subKey, subValue] of Object.entries(value)) {
            const fullKey = this.formatter.join(key, subKey);
            this.flattenKVPair(fkm, fullKey, subValue);
        }
    }
}
//# sourceMappingURL=flat-key-mapper.js.map