import 'package:dio/dio.dart';
import 'package:niogu_ecommerce_v1/core/errors/exceptions.dart';
import 'package:niogu_ecommerce_v1/core/utils/log_message.dart';
import 'package:niogu_ecommerce_v1/features/account/data/datasource/account_remote_datasource_impl.dart';
import 'package:niogu_ecommerce_v1/features/account/data/models/account_model.dart';
import 'package:niogu_ecommerce_v1/features/account/domain/entities/account.dart';
import 'package:niogu_ecommerce_v1/features/account/domain/repositories/i_account_repository.dart';

class AccountRepositoryImpl implements IAccountRepository {
  final IAccountRemoteDatasource _datasource;

  AccountRepositoryImpl(this._datasource);

  @override
  Future<CustomerInfo?> updateCustomer(CustomerInfoRequest request) async {
    try {
      final response = await _datasource.updateCustomer(request);

      final data = response.data;

      if (response.status != 'success' || data == null) return null;

      return data.toCustomerInfo();
    } on DioException catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      throw ServerException("Terjadi kesalahan koneksi");
    }
  }

  @override
  Future<void> updatePassword({
    required String oldPassword,
    required newPassword,
  }) async {
    try {
      await _datasource.updatePassword(
        oldPassword: oldPassword,
        newPassword: newPassword,
      );
    } on DioException catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      throw ServerException("Password lama salah");
    }
  }

  @override
  Future<List<CustomerAddress>> fetchCustomerAddresses() async {
    try {
      final response = await _datasource.fetchCustomerAddresses();

      final data = response.data;

      if (response.status != 'success' || data == null) return [];

      return data.map((address) => address.toCustomerAddress()).toList();
    } on DioException catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      throw ServerException("Terjadi kesalahan koneksi");
    }
  }

  @override
  Future<void> saveCustomerAddress(CustomerAddress address) async {
    try {
      await _datasource.saveCustomerAddress(address.toCustomerAddressModel());
    } on DioException catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      throw ServerException("Terjadi kesalahan koneksi");
    }
  }

  @override
  Future<void> deleteCustomerAddress(String id) async {
    try {
      await _datasource.deleteCustomerAddress(id);
    } on DioException catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      throw ServerException("Terjadi kesalahan koneksi");
    }
  }
}
