import 'package:bloc/bloc.dart';
import 'package:dio/dio.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:hoshan/core/services/api/dio_service.dart';
import 'package:hoshan/data/repository/auth_repository.dart';

part 'ad_remaining_state.dart';

class AdRemainingCubit extends Cubit<AdRemainingState> {
  AdRemainingCubit() : super(AdRemainingInitial());

  void getRemainingAd() async {
    emit(AdRemainingLoading());
    try {
      final response = await DioService().sendRequest().get('/app-metadata');
      final Map<String, dynamic> parsed = {
        for (var item in response.data) item['tag']: item['value']
      };
      final reminding = await AuthRepository.getRemaining();

      parsed['remaining_seconds'] =
          reminding.data['remaining_seconds'].toString();

      emit(AdRemainingSuccess(data: parsed));
    } on DioException catch (e) {
      emit(AdRemainingFail());

      if (kDebugMode) {
        print('Error fetching ad remaining: $e');
      }
    }
  }
}
