// SPDX-License-Identifier: Apache-2.0
import { PatchStrategy, setHeaderOptions, V1ConfigMap, V1ObjectMeta, } from '@kubernetes/client-node';
import { ResourceNotFoundError } from '../../../errors/resource-operation-errors.js';
import { ResourceType } from '../../../resources/resource-type.js';
import { ResourceOperation } from '../../../resources/resource-operation.js';
import { SoloError } from '../../../../../core/errors/solo-error.js';
import { container } from 'tsyringe-neo';
import { K8ClientConfigMap } from './k8-client-config-map.js';
import { InjectTokens } from '../../../../../core/dependency-injection/inject-tokens.js';
import { KubeApiResponse } from '../../../kube-api-response.js';
export class K8ClientConfigMaps {
    kubeClient;
    logger;
    constructor(kubeClient) {
        this.kubeClient = kubeClient;
        this.logger = container.resolve(InjectTokens.SoloLogger);
    }
    async create(namespace, name, labels, data) {
        return await this.createOrReplaceWithForce(namespace, name, labels, data, false, true);
    }
    async createOrReplace(namespace, name, labels, data) {
        return await this.createOrReplaceWithForce(namespace, name, labels, data, false, false);
    }
    async delete(namespace, name) {
        try {
            await this.kubeClient.deleteNamespacedConfigMap({
                name,
                namespace: namespace.name,
            });
            return true;
        }
        catch (error) {
            return KubeApiResponse.isFailingStatus(error);
        }
    }
    async read(namespace, name) {
        try {
            const body = await this.kubeClient.readNamespacedConfigMap({ name, namespace: namespace?.name });
            return K8ClientConfigMap.fromV1ConfigMap(body);
        }
        catch (error) {
            KubeApiResponse.throwError(error, ResourceOperation.READ, ResourceType.CONFIG_MAP, namespace, name);
        }
    }
    async replace(namespace, name, labels, data) {
        return await this.createOrReplaceWithForce(namespace, name, labels, data, true, false);
    }
    async exists(namespace, name) {
        try {
            const cm = await this.read(namespace, name);
            return !!cm;
        }
        catch (error) {
            if (error instanceof ResourceNotFoundError) {
                return false;
            }
            else {
                throw error;
            }
        }
    }
    async createOrReplaceWithForce(namespace, name, labels, data, forceReplace, forceCreate) {
        const replace = await this.shouldReplace(namespace, name, forceReplace, forceCreate);
        const configMap = new V1ConfigMap();
        configMap.data = data;
        const metadata = new V1ObjectMeta();
        metadata.name = name;
        metadata.namespace = namespace.name;
        metadata.labels = labels;
        configMap.metadata = metadata;
        try {
            await (replace
                ? this.kubeClient.replaceNamespacedConfigMap({ name, namespace: namespace.name, body: configMap })
                : this.kubeClient.createNamespacedConfigMap({ namespace: namespace.name, body: configMap }));
            return true;
        }
        catch (error) {
            KubeApiResponse.throwError(error, replace ? ResourceOperation.REPLACE : ResourceOperation.CREATE, ResourceType.CONFIG_MAP, namespace, name);
        }
    }
    async shouldReplace(namespace, name, forceReplace, forceCreate) {
        if (forceReplace && !forceCreate) {
            return true;
        }
        if (forceCreate) {
            return false;
        }
        return await this.exists(namespace, name);
    }
    async list(namespace, labels) {
        const labelSelector = labels ? labels.join(',') : undefined;
        let results;
        try {
            results = await this.kubeClient.listNamespacedConfigMap({
                namespace: namespace.name,
                labelSelector,
            });
        }
        catch (error) {
            KubeApiResponse.throwError(error, ResourceOperation.LIST, ResourceType.CONFIG_MAP, namespace, '');
        }
        return results?.items?.map((v1ConfigMap) => K8ClientConfigMap.fromV1ConfigMap(v1ConfigMap)) || [];
    }
    async listForAllNamespaces(labels) {
        const labelSelector = labels ? labels.join(',') : undefined;
        let results;
        try {
            results = await this.kubeClient.listConfigMapForAllNamespaces({ labelSelector });
        }
        catch (error) {
            KubeApiResponse.throwError(error, ResourceOperation.LIST, ResourceType.CONFIG_MAP, undefined, '');
        }
        return results?.items?.map((v1ConfigMap) => K8ClientConfigMap.fromV1ConfigMap(v1ConfigMap)) || [];
    }
    async update(namespace, name, data) {
        if (!(await this.exists(namespace, name))) {
            throw new ResourceNotFoundError(ResourceOperation.READ, ResourceType.CONFIG_MAP, namespace, name);
        }
        const patch = {
            data: data,
        };
        let result;
        try {
            result = await this.kubeClient.patchNamespacedConfigMap({
                name,
                namespace: namespace.name,
                body: patch,
            }, setHeaderOptions('Content-Type', PatchStrategy.MergePatch));
            this.logger.info(`Patched ConfigMap ${name} in namespace ${namespace}`);
        }
        catch (error) {
            KubeApiResponse.throwError(error, ResourceOperation.UPDATE, ResourceType.CONFIG_MAP, namespace, name);
        }
        if (result) {
            return;
        }
        else {
            throw new SoloError(`Failed to patch ConfigMap ${name} in namespace ${namespace}, no config map returned from patch`);
        }
    }
}
//# sourceMappingURL=k8-client-config-maps.js.map