import { createKubernetesApplyManifestAction } from './k8s-apply';
import { KubernetesObjectApi } from '@kubernetes/client-node';
import * as yaml from 'js-yaml';

jest.mock('@kubernetes/client-node', () => {
	const originalModule = jest.requireActual('@kubernetes/client-node');

	// Mock the entire KubernetesObjectApi module
	return {
		...originalModule,
		KubernetesObjectApi: jest.fn().mockImplementation(() => ({
			create: jest
				.fn()
				.mockImplementation((resource) => Promise.resolve({ body: resource })),
		})),
	};
});

describe('createKubernetesApplyManifestAction', () => {
	const token = process.env.TOKEN!;
	const clusterUrl = process.env.CLUSTER_URL!;

	it('successfully applies a Kubernetes manifest', async () => {
		const catalogClient = {} as any;
		const action = createKubernetesApplyManifestAction(catalogClient);

		const manifest = yaml.dump({
			apiVersion: 'v1',
			kind: 'Pod',
			metadata: { name: 'test-pod', namespace: 'default' },
			spec: { containers: [{ name: 'nginx', image: 'nginx' }] },
		});

		const ctx = {
			input: {
				manifest,
				token: token,
				url: clusterUrl,
			},
			logger: { info: jest.fn() },
		} as any;

		await action.handler(ctx);

		expect(KubernetesObjectApi.prototype.create).toHaveBeenCalledWith(
			expect.objectContaining({
				apiVersion: 'v1',
				kind: 'Pod',
				metadata: expect.objectContaining({
					name: 'test-pod',
					namespace: 'default',
				}),
			})
		);

		expect(ctx.logger.info).toHaveBeenCalledWith(
			expect.stringContaining('Successfully applied manifest')
		);
	});
});
