import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:injectable/injectable.dart';
import '../../../../core/utils/logger.dart';
import '../../domain/entities/compliance_snapshot.dart';
import '../../domain/repositories/compliance_repository.dart';

// Events
abstract class ComplianceEvent extends Equatable {
  const ComplianceEvent();
  @override
  List<Object?> get props => [];
}

class LoadComplianceSnapshot extends ComplianceEvent {
  const LoadComplianceSnapshot();
}

class RefreshComplianceSnapshot extends ComplianceEvent {
  const RefreshComplianceSnapshot();
}

// States
abstract class ComplianceState extends Equatable {
  const ComplianceState();
  @override
  List<Object?> get props => [];
}

class ComplianceInitial extends ComplianceState {
  const ComplianceInitial();
}

class ComplianceLoading extends ComplianceState {
  const ComplianceLoading();
}

class ComplianceLoaded extends ComplianceState {
  final ComplianceSnapshot snapshot;
  const ComplianceLoaded(this.snapshot);
  @override
  List<Object?> get props => [snapshot];
}

class ComplianceError extends ComplianceState {
  final String message;
  const ComplianceError(this.message);
  @override
  List<Object?> get props => [message];
}

@injectable
class ComplianceBloc extends Bloc<ComplianceEvent, ComplianceState> {
  final ComplianceRepository repository;

  ComplianceBloc(this.repository) : super(const ComplianceInitial()) {
    on<LoadComplianceSnapshot>(_onLoad);
    on<RefreshComplianceSnapshot>(_onLoad);
  }

  Future<void> _onLoad(ComplianceEvent event, Emitter<ComplianceState> emit) async {
    emit(const ComplianceLoading());
    try {
      final s = await repository.getSnapshotCurrent();
      emit(ComplianceLoaded(s));
    } catch (e, st) {
      AppLogger.error('ComplianceBloc: load failed', error: e, stackTrace: st);
      emit(ComplianceError(e.toString()));
    }
  }
}
