import 'package:dio/dio.dart';

import '../../../../core/error/custom_error.dart';
import '../../../../core/resources/data_state.dart';
import '../../domain/entities/wallet_entity.dart';
import '../../domain/repository/wallet_repository.dart';
import '../data_source/remote/wallet_api_provider.dart';
import '../model/wallet_model.dart';

class WalletRepositoryImpl extends WalletRepository {
  final WalletApiProvider api;
  WalletRepositoryImpl(this.api);

  @override
  Future<DataState<WalletEntity>> getWallet() async {
    final results = await Future.wait([api.getWallet(), api.getMe()]);
    final Response wallet = results[0];
    final Response me = results[1];
    if (wallet.statusCode == 200 && me.statusCode == 200) {
      return DataSuccess(WalletModel.fromJson(
        Map<String, dynamic>.from(wallet.data as Map),
        Map<String, dynamic>.from((me.data['user'] ?? {}) as Map),
      ));
    }
    return DataError(errorConvertor(wallet.statusCode, null));
  }

  @override
  Future<DataState<int>> claimDaily() async {
    final Response res = await api.claimDaily();
    if (res.statusCode == 200) {
      return DataSuccess((res.data['amount'] ?? 0) as int);
    }
    final d = res.data;
    final msg = (d is Map && d['message'] != null) ? d['message'].toString() : null;
    return DataError(errorConvertor(res.statusCode, msg));
  }
}
