import 'package:bloc/bloc.dart';
import 'package:business_panel/core/config/api_config.dart';
import 'package:business_panel/core/services/token_storage_service.dart';
import 'package:dio/dio.dart';

part 'order_event.dart';
part 'order_state.dart';

class OrderBloc extends Bloc<OrderEvent, OrderState> {
  final Dio _dio = Dio();
  final TokenStorageService _tokenStorage = TokenStorageService();

  OrderBloc() : super(OrderInitial()) {
    on<SubmitOrder>((event, emit) async {
      emit(OrderSubmissionInProgress());
      try {
        final token = await _tokenStorage.getAccessToken();
        if (token == null) {
          emit(OrderSubmissionFailure("خطای احراز هویت."));
          return;
        }

        final response = await _dio.post(
          ApiConfig.addOrder,
          data: {
            'Discount': event.discountId,
            'User': event.userId,
          },
          options: Options(
            headers: {'Authorization': 'Bearer $token'},
          ),
        );

        if (response.statusCode == 200) {
          emit(OrderSubmissionSuccess(response.data['message'] ?? "سفارش با موفقیت ثبت شد."));
        } else {
          emit(OrderSubmissionFailure(response.data['message'] ?? 'خطا در ثبت سفارش.'));
        }
      } on DioException catch (e) {
        emit(OrderSubmissionFailure(e.response?.data['message'] ?? 'خطای شبکه.'));
      } catch (e) {
        emit(OrderSubmissionFailure('خطای پیش‌بینی نشده: ${e.toString()}'));
      }
    });
  }
}