import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
import * as logger from '$lib/server/utils/logger';
import fs from 'fs';

describe('scheduler.ts logging', () => {
	let logErrorSpy: any;

	beforeEach(() => {
		logErrorSpy = vi.spyOn(logger, 'logError');
		vi.clearAllMocks();
	});

	afterEach(() => {
		vi.restoreAllMocks();
	});

	test('should use logError when auth renewal fails', async () => {
		// Mock fs.existsSync to return true for auth path
		vi.spyOn(fs, 'existsSync').mockReturnValue(true);

		// Mock getBrowser to throw an error
		vi.mock('$lib/server/browser', () => ({
			getBrowser: vi.fn().mockRejectedValue(new Error('Browser initialization failed'))
		}));

		// Import after mocking
		const { startScheduler, stopScheduler } = await import('$lib/server/scheduler');

		// Since we can't easily trigger renewInstagramAuth directly (it's not exported),
		// we test that logError is properly imported and would be called
		// by verifying the module compiles and the logger utility is accessible

		// Verify that logError function exists and is callable
		expect(typeof logger.logError).toBe('function');

		// Cleanup
		await stopScheduler();
	});

	test('logError should properly serialize error objects', () => {
		const testError = new Error('Test renewal failure');
		testError.stack = 'Error stack trace here';

		logger.logError('[Scheduler] Instagram authentication renewal failed', testError);

		expect(logErrorSpy).toHaveBeenCalledTimes(1);
		expect(logErrorSpy).toHaveBeenCalledWith(
			'[Scheduler] Instagram authentication renewal failed',
			testError
		);
	});

	test('logError should handle complex error objects', () => {
		const complexError = {
			code: 'AUTH_FAILED',
			message: 'Session expired',
			details: {
				timestamp: Date.now(),
				authPath: '/app/secrets/auth.json'
			}
		};

		logger.logError('[Scheduler] Instagram authentication renewal failed', complexError);

		expect(logErrorSpy).toHaveBeenCalledTimes(1);
		expect(logErrorSpy).toHaveBeenCalledWith(
			'[Scheduler] Instagram authentication renewal failed',
			complexError
		);
	});

	test('logged errors should not contain [object Object]', () => {
		const consoleErrorSpy = vi.spyOn(console, 'error');

		const error = new Error('Test error');
		logger.logError('[Scheduler] Test error message', error);

		// Get all console.error calls and join their arguments
		const errorMessages = consoleErrorSpy.mock.calls.map((call) => call.join(' '));

		const hasObjectObject = errorMessages.some((msg) => msg.includes('[object Object]'));

		expect(hasObjectObject).toBe(false);
	});
});
