import 'package:flutter_bloc/flutter_bloc.dart';

import 'workflow_event.dart';
import 'workflow_state.dart';

/// Bloc, der den Detail-Workflow einer einzelnen Lieferung trägt.
///
/// Pro `DeliveryDetail`-Page-Push neu instanziert (per `BlocProvider` direkt
/// in der Page), Lifetime endet beim Pop. Strukturelle Persistenzen
/// (Notizen speichern, Artikel entfernen, Complete) gehen NICHT durch
/// diesen Bloc, sondern direkt am globalen `TourBloc` — der Workflow-Bloc
/// trägt nur Step-State + lokale Drafts.
class DeliveryWorkflowBloc
    extends Bloc<DeliveryWorkflowEvent, DeliveryWorkflowState> {
  DeliveryWorkflowBloc({required String deliveryId})
      : super(DeliveryWorkflowState.initial(deliveryId)) {
    on<WorkflowGoToStep>((e, emit) => emit(state.copyWith(step: e.step)));
    on<WorkflowNextStep>((e, emit) {
      final next = state.step.index + 1;
      if (next < WorkflowStep.values.length) {
        emit(state.copyWith(step: WorkflowStep.values[next]));
      }
    });
    on<WorkflowPreviousStep>((e, emit) {
      final prev = state.step.index - 1;
      if (prev >= 0) {
        emit(state.copyWith(step: WorkflowStep.values[prev]));
      }
    });
    on<WorkflowAddPendingImage>((e, emit) {
      final next = [
        ...state.pendingImageNotes,
        PendingImageNote(file: e.file, pickedAt: DateTime.now()),
      ];
      emit(state.copyWith(pendingImageNotes: next));
    });
    on<WorkflowRemovePendingImage>((e, emit) {
      if (e.index < 0 || e.index >= state.pendingImageNotes.length) return;
      final next = [...state.pendingImageNotes]..removeAt(e.index);
      emit(state.copyWith(pendingImageNotes: next));
    });
    on<WorkflowOverridePaymentMethod>((e, emit) => emit(
          state.copyWith(paymentMethodOverrideId: e.paymentMethodId),
        ));
  }
}
