import 'dart:developer';

import 'package:dartz/dartz.dart';
import 'package:injectable/injectable.dart';

import '../../../domain/product/product.dart';
import '../datasources/remote_data_provider.dart';

@Injectable(as: IProductRepository)
class ProductRepository implements IProductRepository {
  final ProductRemoteDataProvider _dataProvider;
  final String _logName = 'ProductRepository';

  ProductRepository(this._dataProvider);

  @override
  Future<Either<ProductFailure, List<Product>>> get({
    int page = 1,
    int limit = 10,
    String? categoryId,
    String? search,
  }) async {
    try {
      final result = await _dataProvider.fetch(
        page: page,
        limit: limit,
        categoryId: categoryId,
        search: search,
      );

      if (result.hasError) {
        return left(result.error!);
      }

      final auth = result.data!.map((e) => e.toDomain()).toList();

      return right(auth);
    } catch (e, s) {
      log('getProductError', name: _logName, error: e, stackTrace: s);
      return left(const ProductFailure.unexpectedError());
    }
  }
}
