import 'package:be_happy/core/result.dart';
import 'package:be_happy/domain/entities/client_subscription.dart';
import 'package:be_happy/domain/entities/subscription.dart';
import 'package:be_happy/domain/usecase/get_available_subscriptions_usecase.dart';
import 'package:be_happy/domain/usecase/get_client_subscriptions_usecase.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../event/subscription_list_event.dart';
import '../state/subscription_list_state.dart';

class SubscriptionListBloc extends Bloc<SubscriptionEvent, SubscriptionState> {
  final GetAvailableSubscriptionsUsecase getAvailableSubscriptionsUsecase;
  final GetClientSubscriptionsUsecase getClientSubscriptionsUsecase;


  SubscriptionListBloc({
    required this.getAvailableSubscriptionsUsecase,
    required this.getClientSubscriptionsUsecase,
  }) : super(SubscriptionsLoading()) {
    on<LoadSubscriptionsEvent>((event, emit) async {
      emit(SubscriptionsLoading());
      try {
        final results = await Future.wait([
          getAvailableSubscriptionsUsecase(),
          getClientSubscriptionsUsecase(),
        ]);

        final allResult = results[0];
        final activeResult = results[1] ;

        if (allResult is Success<List<Subscription>> && activeResult is Success<List<ClientSubscription>>) {
          final availableSubs = allResult.data ?? [];
          final clientSubs = activeResult.data ?? [];

          final Map<int, Subscription> combinedSubsMap = {};

          for (var clientSub in clientSubs) {
            if (clientSub.subscription != null) {
              combinedSubsMap[clientSub.subscriptionId] = clientSub.subscription;
            }
          }

          for (var sub in availableSubs) {
            combinedSubsMap[sub.id] = sub;
          }

          emit(SubscriptionsLoaded(
            subscriptions: combinedSubsMap.values.toList(),
            activeSubscriptions: clientSubs,
          ));
        } else {
          emit(SubscriptionsError("Не удалось загрузить данные из API"));
        }
      } catch (e) {
        emit(SubscriptionsError(e.toString()));
      }
    });
  }
}
