// SPDX-License-Identifier: Apache-2.0
import { V1ObjectMeta, V1Service, V1ServicePort, V1ServiceSpec, } from '@kubernetes/client-node';
import { K8ClientBase } from '../../k8-client-base.js';
import { KubeApiResponse } from '../../../kube-api-response.js';
import { ResourceOperation } from '../../../resources/resource-operation.js';
import { ResourceType } from '../../../resources/resource-type.js';
import { K8ClientService } from './k8-client-service.js';
import { SoloError } from '../../../../../core/errors/solo-error.js';
export class K8ClientServices extends K8ClientBase {
    kubeClient;
    constructor(kubeClient) {
        super();
        this.kubeClient = kubeClient;
    }
    async list(namespace, labels) {
        const labelSelector = labels ? labels.join(',') : undefined;
        const serviceList = await this.kubeClient.listNamespacedService(namespace.name, undefined, undefined, undefined, undefined, labelSelector);
        KubeApiResponse.check(serviceList.response, ResourceOperation.LIST, ResourceType.SERVICE, namespace, '');
        return serviceList.body.items.map((svc) => {
            return this.wrapService(namespace, svc);
        });
    }
    async read(namespace, name) {
        const svc = await this.readV1Service(namespace, name);
        if (!svc) {
            return null;
        }
        return this.wrapService(namespace, svc);
    }
    async readV1Service(namespace, name) {
        const { response, body } = await this.kubeClient.readNamespacedService(name, namespace.name);
        KubeApiResponse.check(response, ResourceOperation.READ, ResourceType.SERVICE, namespace, name);
        return body;
    }
    wrapService(_namespace, svc) {
        return new K8ClientService(this.wrapObjectMeta(svc.metadata), svc.spec, svc.status);
    }
    async create(serviceReference, labels, servicePort, podTargetPort) {
        const v1SvcMetadata = new V1ObjectMeta();
        v1SvcMetadata.name = serviceReference.name.toString();
        v1SvcMetadata.namespace = serviceReference.namespace.toString();
        v1SvcMetadata.labels = labels;
        const v1SvcPort = new V1ServicePort();
        v1SvcPort.port = servicePort;
        v1SvcPort.targetPort = podTargetPort;
        const v1SvcSpec = new V1ServiceSpec();
        v1SvcSpec.ports = [v1SvcPort];
        const v1Svc = new V1Service();
        v1Svc.metadata = v1SvcMetadata;
        v1Svc.spec = v1SvcSpec;
        let result;
        try {
            result = await this.kubeClient.createNamespacedService(serviceReference.namespace.toString(), v1Svc);
        }
        catch (error) {
            throw new SoloError('Failed to create service', error);
        }
        KubeApiResponse.check(result.response, ResourceOperation.CREATE, ResourceType.SERVICE, serviceReference.namespace, serviceReference.name.toString());
        return this.wrapService(serviceReference.namespace, result.body);
    }
}
//# sourceMappingURL=k8-client-services.js.map