// SPDX-License-Identifier: Apache-2.0
import { StorageOperation } from '../api/storage-operation.js';
import { MissingArgumentError } from '../../../core/errors/missing-argument-error.js';
import { StorageBackendError } from '../api/storage-backend-error.js';
/**
 * ConfigMapStorageBackend is a storage backend that uses a {@link ConfigMap} to store data.
 * The key will be the name of the property within the data object within the ConfigMap.
 */
export class ConfigMapStorageBackend {
    configMap;
    constructor(configMap) {
        this.configMap = configMap;
        if (!this.configMap) {
            throw new MissingArgumentError('ConfigMapStorageBackend is missing the configMap argument');
        }
    }
    async delete(key) {
        try {
            const data = this.configMap.data;
            if (data && Object.keys(data).length > 0 && data.hasOwnProperty(key)) {
                delete data[key];
            }
            else {
                throw new StorageBackendError(`key: ${key} not found in config map`);
            }
        }
        catch (error) {
            throw error instanceof StorageBackendError
                ? error
                : new StorageBackendError(`error deleting config map data key: ${key}`, error);
        }
    }
    isSupported(op) {
        switch (op) {
            case StorageOperation.List:
            case StorageOperation.ReadBytes:
            case StorageOperation.WriteBytes:
            case StorageOperation.Delete: {
                return true;
            }
            default: {
                return false;
            }
        }
    }
    async list() {
        const data = this.configMap.data;
        return data ? Object.keys(data) : [];
    }
    async readBytes(key) {
        try {
            const data = this.configMap.data;
            if (data && Object.keys(data).length > 0) {
                const value = data[key];
                return Buffer.from(value, 'utf8');
            }
            else {
                throw new StorageBackendError(`config map is empty: ${key}`);
            }
        }
        catch (error) {
            throw error instanceof StorageBackendError
                ? error
                : new StorageBackendError(`error reading config map: ${key}`, error);
        }
    }
    async writeBytes(key, data) {
        try {
            this.configMap.data[key] = data.toString('utf8');
        }
        catch (error) {
            throw error instanceof StorageBackendError
                ? error
                : new StorageBackendError(`error writing config map: ${key}`, error);
        }
    }
}
//# sourceMappingURL=config-map-storage-backend.js.map