/// Tests unitaires pour SendBroadcast use case
library send_broadcast_test;

import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:dartz/dartz.dart';
import 'package:unionflow_mobile_apps/features/communication/domain/usecases/send_broadcast.dart';
import 'package:unionflow_mobile_apps/features/communication/domain/repositories/messaging_repository.dart';
import 'package:unionflow_mobile_apps/features/communication/domain/entities/message.dart';
import 'package:unionflow_mobile_apps/core/error/failures.dart';

@GenerateMocks([MessagingRepository])
import 'send_broadcast_test.mocks.dart';

void main() {
  late SendBroadcast useCase;
  late MockMessagingRepository mockRepository;

  setUp(() {
    mockRepository = MockMessagingRepository();
    useCase = SendBroadcast(mockRepository);
  });

  group('SendBroadcast Use Case', () {
    const tOrgId = 'org-123';
    const tSubject = 'Assemblée Générale 2024';
    const tContent = 'Chers membres, l\'AG aura lieu le 20 décembre...';
    final tBroadcastMessage = Message(
      id: 'broadcast-1',
      conversationId: 'broadcast-conv',
      senderId: 'admin-1',
      senderName: 'Admin Organisation',
      content: tContent,
      type: MessageType.broadcast,
      status: MessageStatus.sent,
      priority: MessagePriority.high,
      recipientIds: ['all'],
      organizationId: tOrgId,
      createdAt: DateTime.now(),
      metadata: {'subject': tSubject},
    );

    test('should send broadcast message successfully', () async {
      // Arrange
      when(mockRepository.sendBroadcast(
        organizationId: tOrgId,
        subject: tSubject,
        content: tContent,
        priority: anyNamed('priority'),
        attachments: anyNamed('attachments'),
      )).thenAnswer((_) async => Right(tBroadcastMessage));

      // Act
      final result = await useCase(
        organizationId: tOrgId,
        subject: tSubject,
        content: tContent,
      );

      // Assert
      expect(result, Right(tBroadcastMessage));
      result.fold(
        (failure) => fail('Should not return failure'),
        (message) {
          expect(message.type, equals(MessageType.broadcast));
          expect(message.content, equals(tContent));
          expect(message.metadata?['subject'], equals(tSubject));
        },
      );
      verify(mockRepository.sendBroadcast(
        organizationId: tOrgId,
        subject: tSubject,
        content: tContent,
        priority: MessagePriority.normal,
        attachments: null,
      ));
      verifyNoMoreInteractions(mockRepository);
    });

    test('should send urgent broadcast with attachments', () async {
      // Arrange
      final attachments = ['document.pdf', 'plan.jpg'];
      final urgentBroadcast = Message(
        id: 'broadcast-urgent',
        conversationId: 'broadcast-conv',
        senderId: 'admin-1',
        senderName: 'Admin Organisation',
        content: 'URGENT: Annulation événement',
        type: MessageType.broadcast,
        status: MessageStatus.sent,
        priority: MessagePriority.urgent,
        recipientIds: ['all'],
        organizationId: tOrgId,
        attachments: attachments,
        createdAt: DateTime.now(),
      );
      when(mockRepository.sendBroadcast(
        organizationId: tOrgId,
        subject: 'URGENT',
        content: 'URGENT: Annulation événement',
        priority: MessagePriority.urgent,
        attachments: attachments,
      )).thenAnswer((_) async => Right(urgentBroadcast));

      // Act
      final result = await useCase(
        organizationId: tOrgId,
        subject: 'URGENT',
        content: 'URGENT: Annulation événement',
        priority: MessagePriority.urgent,
        attachments: attachments,
      );

      // Assert
      result.fold(
        (failure) => fail('Should not return failure'),
        (message) {
          expect(message.priority, equals(MessagePriority.urgent));
          expect(message.attachments, equals(attachments));
        },
      );
    });

    test('should return ValidationFailure when subject or content is empty', () async {
      // Act
      final result = await useCase(
        organizationId: tOrgId,
        subject: '',
        content: 'Content',
      );

      // Assert
      result.fold(
        (failure) {
          expect(failure, isA<ValidationFailure>());
        },
        (message) => fail('Should not return message'),
      );
      verifyZeroInteractions(mockRepository);
    });

    test('should return ServerFailure when repository fails', () async {
      // Arrange
      final tFailure = ServerFailure('Erreur d\'envoi broadcast');
      when(mockRepository.sendBroadcast(
        organizationId: anyNamed('organizationId'),
        subject: anyNamed('subject'),
        content: anyNamed('content'),
        priority: anyNamed('priority'),
        attachments: anyNamed('attachments'),
      )).thenAnswer((_) async => Left(tFailure));

      // Act
      final result = await useCase(
        organizationId: tOrgId,
        subject: tSubject,
        content: tContent,
      );

      // Assert
      expect(result, Left(tFailure));
      result.fold(
        (failure) => expect(failure, isA<ServerFailure>()),
        (message) => fail('Should not return message'),
      );
    });
  });
}
