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/profile_entity.dart';
import '../../domain/repository/profile_repository.dart';
import '../data_source/remote/profile_api_provider.dart';
import '../model/profile_model.dart';

class ProfileRepositoryImpl extends ProfileRepository {
  final ProfileApiProvider api;
  ProfileRepositoryImpl(this.api);

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

  @override
  Future<DataState<String>> updateProfile(ProfileParams params) async {
    final Response res = await api.updateProfile(params.firstName, params.avatar);
    if (res.statusCode == 200) return const DataSuccess('ok');
    final d = res.data;
    final msg = (d is Map && d['message'] != null) ? d['message'].toString() : null;
    return DataError(errorConvertor(res.statusCode, msg));
  }
}
