// src/services/queueService.server.test.ts
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { logger as mockLogger } from './logger.server';
import { EventEmitter } from 'node:events';
import type { Job, Worker } from 'bullmq';
import type { Mock } from 'vitest';

// Define interfaces for our mock constructors to avoid using `any` for the `this` context.
interface MockWorkerInstance {
  name: string;
  on: Mock;
  close: Mock<() => Promise<void>>;
  isRunning: Mock<() => boolean>;
}

interface MockQueueInstance {
  name: string;
  add: Mock;
  close: Mock<() => Promise<void>>;
}

// --- Inline Mock Implementations ---

// Create a single, shared mock Redis connection instance that we can control in tests.
const mockRedisConnection = new EventEmitter() as EventEmitter & { ping: Mock };
mockRedisConnection.ping = vi.fn().mockResolvedValue('PONG');

// Mock the 'ioredis' library. The default export is a class constructor.
// We make it a mock function that returns our shared `mockRedisConnection` instance.
vi.mock('ioredis', () => ({
  default: vi.fn(function() {
    return mockRedisConnection;
  }),
}));

// Mock the 'bullmq' library.
vi.mock('bullmq', () => ({
  // Mock the Worker class constructor.
  Worker: vi.fn(function (this: MockWorkerInstance, name: string) {
    this.name = name;
    this.on = vi.fn();
    this.close = vi.fn().mockResolvedValue(undefined);
    this.isRunning = vi.fn().mockReturnValue(true);
    return this;
  }),
  // Mock the Queue class constructor.
  Queue: vi.fn(function (this: MockQueueInstance, name: string) {
    this.name = name;
    this.add = vi.fn();
    this.close = vi.fn().mockResolvedValue(undefined);
    return this;
  }),
}));

vi.mock('./logger.server', () => ({
  logger: {
    info: vi.fn(),
    error: vi.fn(),
    warn: vi.fn(),
    debug: vi.fn(),
  },
}));

// Mock other dependencies that are not the focus of this test file.
vi.mock('./aiService.server');
vi.mock('./emailService.server');
vi.mock('./db/index.db');

describe('Queue Service Setup and Lifecycle', () => {
  let gracefulShutdown: (signal: string) => Promise<void>;
  let flyerWorker: Worker, emailWorker: Worker, analyticsWorker: Worker, cleanupWorker: Worker;

  beforeEach(async () => {
    vi.clearAllMocks();
    // Reset modules to re-evaluate the queueService.server.ts file with fresh mocks
    // This ensures that new worker and queue instances are created for each test.
    vi.resetModules();

    // Dynamically import the modules after mocks are set up
    const queueService = await import('./queueService.server');

    // Capture the imported instances for use in tests
    gracefulShutdown = queueService.gracefulShutdown;
    flyerWorker = queueService.flyerWorker;
    emailWorker = queueService.emailWorker;
    analyticsWorker = queueService.analyticsWorker;
    cleanupWorker = queueService.cleanupWorker;
  });

  afterEach(() => {
    // Clean up all event listeners on the mock connection to prevent open handles.
    mockRedisConnection.removeAllListeners();
  });

  it('should log a success message when Redis connects', () => {
    // Act: Simulate the 'connect' event on the mock Redis connection
    mockRedisConnection.emit('connect');

    // Assert: Check if the logger was called with the expected message
    expect(mockLogger.info).toHaveBeenCalledWith('[Redis] Connection established successfully.');
  });

  it('should log an error message when Redis connection fails', () => {
    const redisError = new Error('Connection refused');
    mockRedisConnection.emit('error', redisError);
    expect(mockLogger.error).toHaveBeenCalledWith({ err: redisError }, '[Redis] Connection error.');
  });

  it('should attach completion and failure listeners to all workers', () => {
    // The workers are instantiated when the module is imported in beforeEach.
    // We just need to check that the 'on' method was called for each event.
    const workers = [flyerWorker, emailWorker, analyticsWorker, cleanupWorker];
    for (const worker of workers) {
      expect(worker.on).toHaveBeenCalledWith('completed', expect.any(Function));
      expect(worker.on).toHaveBeenCalledWith('failed', expect.any(Function));
    }
  });

  describe('Worker Event Listeners', () => {
    it('should log a message when a job is completed', () => {
      // Find the 'completed' callback registered on our mock worker.
      const completedCallback = (flyerWorker.on as Mock).mock.calls.find(call => call[0] === 'completed')?.[1];
      // Ensure the callback was found before trying to call it
      expect(completedCallback).toBeDefined();

      const mockJob = { id: 'job-abc' };
      const mockReturnValue = { flyerId: 123 };

      // Call the captured callback
      (completedCallback as (job: Job, result: unknown) => void)(mockJob as Job, mockReturnValue);

      expect(mockLogger.info).toHaveBeenCalledWith(
        { returnValue: mockReturnValue },
        `[flyer-processing] Job job-abc completed successfully.`
      );
    });

    it('should log an error when a job has ultimately failed', () => {
      // Find the 'failed' callback registered on our mock worker.
      const failedCallback = (emailWorker.on as Mock).mock.calls.find(call => call[0] === 'failed')?.[1];
      expect(failedCallback).toBeDefined();

      const mockJob = { id: 'job-xyz', data: { to: 'test@example.com' } };
      const mockError = new Error('SMTP Server Down');

      // Call the captured callback
      (failedCallback as (job: Job | undefined, error: Error) => void)(mockJob as Job, mockError);

      expect(mockLogger.error).toHaveBeenCalledWith(
        { err: mockError, jobData: mockJob.data },
        `[email-sending] Job ${mockJob.id} has ultimately failed after all attempts.`
      );
    });
  });

  describe('gracefulShutdown', () => {
    let processExitSpy: Mock;

    beforeEach(() => {
      processExitSpy = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never);
    });

    afterEach(() => {
      processExitSpy.mockRestore();
    });

    it('should close all workers and exit the process', async () => {
      await gracefulShutdown('SIGINT');
      expect((flyerWorker as unknown as MockQueueInstance).close).toHaveBeenCalled();
      expect((emailWorker as unknown as MockQueueInstance).close).toHaveBeenCalled();
      expect((analyticsWorker as unknown as MockQueueInstance).close).toHaveBeenCalled();
      expect((cleanupWorker as unknown as MockQueueInstance).close).toHaveBeenCalled();
      expect(mockLogger.info).toHaveBeenCalledWith('[Shutdown] All workers have been closed.');
      expect(processExitSpy).toHaveBeenCalledWith(0);
    });
  });
});