// Importing necessary modules and functions for the test
import createKubernetesApplyManifestAction from './k8s-apply';
import { KubernetesObjectApi } from '@kubernetes/client-node';
import { TemplateAction } from '@backstage/plugin-scaffolder-backend';
import { JsonObject } from '@backstage/config';

jest.mock('fs');
jest.mock('@kubernetes/client-node', () => {
	const original = jest.requireActual('@kubernetes/client-node');
	return {
		...original,
		KubernetesObjectApi: {
			makeApiClient: jest.fn().mockReturnValue({
				create: jest.fn().mockResolvedValue({}),
			}),
		},
	};
});
jest.mock('js-yaml');

jest.mock('fs', () => ({
	readFileSync: jest.fn().mockImplementation(() => 'mocked file content'),
}));

type ActionContext = {
	input: {
		manifestPath: string;
	};
	logger: {
		info: jest.Mock<any, any>;
		error: jest.Mock<any, any>;
	};
	logStream: {
		write: jest.Mock<any, any>;
	};
	workspacePath: string;
	output: (name: string, value: any) => void;
	createTemporaryDirectory: () => Promise<string>;
};

describe('createKubernetesApplyManifestAction', () => {
	let action: TemplateAction<JsonObject>;

	beforeAll(() => {
		action = createKubernetesApplyManifestAction();
	});

	it('successfully applies a Kubernetes manifest from file, using environment variables for configuration', async () => {
		expect(process.env.TOKEN).toBeDefined();
		expect(process.env.CLUSTER_URL).toBeDefined();

		const mockContext: ActionContext = {
			input: {
				manifestPath: './manifests/ns.yaml',
			},
			logger: {
				info: jest.fn(),
				error: jest.fn(),
			},
			logStream: {
				write: jest.fn(),
			},
			workspacePath: '/tmp',
			output: jest.fn(),
			createTemporaryDirectory: jest
				.fn()
				.mockResolvedValue('/tmp/mock-temp-dir'),
		};

		await action.handler(mockContext);

		expect(KubernetesObjectApi.makeApiClient).toHaveBeenCalled();

		expect(mockContext.logger.info).toHaveBeenCalled();
	});
});
