/**
* Copyright Super iPaaS Integration LLC, an IBM Company 2024
*/
import winston from 'winston';
import { getLogger, createLoggerInstance } from '../src/utils.js';
import DailyRotateFile from 'winston-daily-rotate-file';

jest.mock('../src/logger-config.js', () => ({
	__esModule: true,
	LoggerConfig: {
		getLoggerFormat: jest.fn().mockReturnValue('text'),
		getFilename: jest.fn().mockReturnValue('logs/logfile.log'),
		getDatePattern: jest.fn().mockReturnValue('YYYY-MM-DD'),
		getZippedArchive: jest.fn().mockReturnValue(false),
		getMaxSize: jest.fn().mockReturnValue('10m'),
		getMaxFiles: jest.fn().mockReturnValue('10d'),
	},
}));

describe('Logger', () => {
	beforeEach(() => {
		jest.clearAllMocks();
	});

	describe('getLogger', () => {
		it('should return an existing logger', () => {
			const moduleName = 'TestModule';
			winston.loggers.get = jest.fn().mockReturnValue({} as winston.Logger);

			const logger = getLogger(moduleName);

			expect(winston.loggers.get).toHaveBeenCalledWith(moduleName);
			expect(logger).toStrictEqual({} as winston.Logger);
		});

		it('should return undefined for a non-existent logger', () => {
			const moduleName = 'NonExistentModule';
			winston.loggers.get = jest.fn().mockReturnValue(undefined);

			const logger = getLogger(moduleName);

			expect(winston.loggers.get).toHaveBeenCalledWith(moduleName);
			expect(logger).toBeUndefined();
		});
	});
	describe('createLoggerInstance', () => {
		process.env.STU_CONSOLE_LOG_ENABLED='true';
		process.env.STU_FILE_LOG_ENABLED='true';
		it('should use the configured log format', () => {
			const moduleName = 'TestModule';
			const loggerInstance = createLoggerInstance(moduleName);
	
			expect(loggerInstance.format).toEqual(expect.any(Object));
		});
	
		it('should add console and DailyRotateFile transports', () => {

			const moduleName = 'TestModule';
			const loggerInstance = createLoggerInstance(moduleName);
	
			expect(loggerInstance.transports).toHaveLength(2);
			expect(loggerInstance.transports[0]).toBeInstanceOf(DailyRotateFile);
			expect(loggerInstance.transports[1]).toBeInstanceOf(winston.transports.Console);
	
			const rotateFileTransport = loggerInstance.transports[0];
			const options = (rotateFileTransport as DailyRotateFile).options;
			
			expect(options.filename).toBe('logs/logfile.log');
			expect(options.datePattern).toBe('YYYY-MM-DD');
			expect(options.zippedArchive).toBe(false);
			expect(options.maxSize).toBe('10m');
			expect(options.maxFiles).toBe('10d');
		});
	});
});
