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/product/data/datasource/product_datasource_remote_impl.dart';
import 'package:niogu_ecommerce_v1/features/product/domain/entities/product.dart';
import 'package:niogu_ecommerce_v1/features/product/domain/repositories/i_product_repository.dart';

class ProductRepositoryImpl implements IProductRepository {
  final IProductDatasourceRemote _datasource;

  ProductRepositoryImpl(this._datasource);

  @override
  Future<ProductDetail?> fetchProductById(String id) async {
    try {
      final response = await _datasource.fetchProductById(id);

      final productDetail = response.data;

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

      return productDetail.toProductDetail();
    } on DioException catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);

      throw ServerException("Terjadi kesalahan koneksi");
    }
  }
}
