import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../core/network/api_client.dart';
import 'wallet.dart';

enum WalletStatus { initial, loading, loaded, error }

class WalletState extends Equatable {
  final WalletStatus status;
  final Wallet? wallet;

  const WalletState({this.status = WalletStatus.initial, this.wallet});

  @override
  List<Object?> get props => [status, wallet];
}

class WalletCubit extends Cubit<WalletState> {
  final ApiClient _api;
  WalletCubit(this._api) : super(const WalletState());

  Future<void> load() async {
    emit(const WalletState(status: WalletStatus.loading));
    try {
      final res = await _api.dio.get('/wallet');
      emit(WalletState(
        status: WalletStatus.loaded,
        wallet: Wallet.fromJson(Map<String, dynamic>.from(res.data)),
      ));
    } catch (_) {
      emit(const WalletState(status: WalletStatus.error));
    }
  }

  /// دریافت سکه روزانه و سپس به‌روزرسانی کیف‌پول.
  Future<int?> claimDaily() async {
    try {
      final res = await _api.dio.post('/rewards/daily');
      await load();
      return (res.data['amount'] ?? 0) as int;
    } catch (_) {
      return null;
    }
  }
}
