import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { Notification } from '../../domain/entities/Notification';
import { NotificationRepository } from '../../domain/repositories/NotificationRepository';
import {
    GetUnreadNotificationsUseCase,
    type GetUnreadNotificationsInput,
} from './GetUnreadNotificationsUseCase';

interface NotificationRepositoryMock {
  findUnreadByRecipientId: Mock;
}

describe('GetUnreadNotificationsUseCase', () => {
  let notificationRepository: NotificationRepositoryMock;
  let logger: Logger;
  let useCase: GetUnreadNotificationsUseCase;

  beforeEach(() => {
    notificationRepository = {
      findUnreadByRecipientId: vi.fn(),
    };

    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger;

    useCase = new GetUnreadNotificationsUseCase(
      notificationRepository as unknown as NotificationRepository,
      logger,
    );
  });

  it('returns unread notifications and total count', async () => {
    const recipientId = 'driver-1';
    const notifications: Notification[] = [
      Notification.create({
        id: 'n1',
        recipientId,
        type: 'system_announcement',
        title: 'Test',
        body: 'Body',
        channel: 'in_app',
      }),
    ];

    notificationRepository.findUnreadByRecipientId.mockResolvedValue(notifications);

    const input: GetUnreadNotificationsInput = { recipientId };

    const result = await useCase.execute(input);

    expect(notificationRepository.findUnreadByRecipientId).toHaveBeenCalledWith(recipientId);
    expect(result).toBeInstanceOf(Result);
    expect(result.isOk()).toBe(true);
    
    const successResult = result.unwrap();
    expect(successResult.notifications).toEqual(notifications);
    expect(successResult.totalCount).toBe(1);
  });

  it('handles repository errors by logging and returning error result', async () => {
    const recipientId = 'driver-1';
    const error = new Error('DB error');
    notificationRepository.findUnreadByRecipientId.mockRejectedValue(error);

    const input: GetUnreadNotificationsInput = { recipientId };

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<'REPOSITORY_ERROR', { message: string }>;
    expect(err.code).toBe('REPOSITORY_ERROR');
    expect(err.details.message).toBe('DB error');
    expect((logger.error as unknown as Mock)).toHaveBeenCalled();
  });
});
