import 'package:dio/dio.dart';

import '../../../../core/error/custom_error.dart';
import '../../../../core/resources/data_state.dart';
import '../../../../core/usecase/use_case.dart';
import '../../domain/entities/shop_entities.dart';
import '../../domain/repository/shop_repository.dart';
import '../data_source/remote/shop_api_provider.dart';
import '../model/shop_models.dart';

class ShopRepositoryImpl extends ShopRepository {
  final ShopApiProvider api;
  ShopRepositoryImpl(this.api);

  @override
  Future<DataState<ShopData>> getShop() async {
    final Response res = await api.getShop();
    if (res.statusCode == 200) {
      return DataSuccess(
          ShopMapper.shopData(Map<String, dynamic>.from(res.data as Map)));
    }
    return DataError(errorConvertor(res.statusCode, _msg(res)));
  }

  @override
  Future<DataState<String>> buyCard(String cardId) async {
    final Response res = await api.buyCard(cardId);
    if (res.statusCode == 200) return const DataSuccess('کارت خریداری شد');
    return DataError(errorConvertor(res.statusCode, _msg(res)));
  }

  @override
  Future<DataState<String>> selectCard(String cardId) async {
    final Response res = await api.selectCard(cardId);
    if (res.statusCode == 200) return const DataSuccess('کارت انتخاب شد');
    return DataError(errorConvertor(res.statusCode, _msg(res)));
  }

  @override
  Future<DataState<String>> purchase(PurchaseParams params) async {
    final Response res = await api.purchase(
      store: params.store,
      kind: params.kind,
      productId: params.productId,
      token: params.token,
      purchaseData: params.purchaseData,
      signature: params.signature,
    );
    if (res.statusCode == 200) return const DataSuccess('خرید با موفقیت انجام شد');
    return DataError(errorConvertor(res.statusCode, _msg(res)));
  }

  @override
  Future<DataState<int>> adReward(String token) async {
    final Response res = await api.adReward(token);
    if (res.statusCode == 200) {
      return DataSuccess((res.data['amount'] ?? 0) as int);
    }
    return DataError(errorConvertor(res.statusCode, _msg(res)));
  }

  String? _msg(Response res) {
    final d = res.data;
    if (d is Map && d['message'] != null) return d['message'].toString();
    return null;
  }
}
