import 'package:dio/dio.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:injectable/injectable.dart';

import '../../data/repositories/finance_repository.dart';
import 'finance_event.dart';
import 'finance_state.dart';

@injectable
class FinanceBloc extends Bloc<FinanceEvent, FinanceState> {
  final FinanceRepository _repository;

  FinanceBloc(this._repository) : super(FinanceInitial()) {
    on<LoadFinanceRequested>(_onLoadFinanceRequested);
    on<FinancePaymentInitiated>(_onFinancePaymentInitiated);
  }

  Future<void> _onLoadFinanceRequested(LoadFinanceRequested event, Emitter<FinanceState> emit) async {
    emit(FinanceLoading());
    try {
      final summary = await _repository.getFinancialSummary();
      final transactions = await _repository.getTransactions();
      emit(FinanceLoaded(summary: summary, transactions: transactions));
    } catch (e) {
      if (e is DioException && e.type == DioExceptionType.cancel) return;
      emit(FinanceError('Erreur chargement des finances: $e'));
    }
  }

  void _onFinancePaymentInitiated(FinancePaymentInitiated event, Emitter<FinanceState> emit) {
    // Intégration paiement: appeler le service Wave ou Orange Money (API paiement) selon le design métier.
    // Pour l'instant, la transaction est gérée côté UI (payment_dialog) et le BLoC reste en FinanceLoaded.
    if (state is FinanceLoaded) {
      // Option: émettre FinancePaymentPending puis FinanceLoaded après confirmation API.
    }
  }
}
