import 'dart:developer';

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

import '../../../domain/order/order.dart';
import '../../outlet/datasource/local_data_provider.dart';
import '../datasource/remote_data_provider.dart';

@Injectable(as: IOrderRepository)
class OrderRepository implements IOrderRepository {
  final OrderRemoteDataProvider _dataProvider;
  final OutletLocalDataProvider _outletLocalDataProvider;
  final String _logName = 'OrderRepository';

  OrderRepository(this._dataProvider, this._outletLocalDataProvider);

  @override
  Future<Either<OrderFailure, List<Order>>> get({
    int page = 1,
    int limit = 20,
    String? status,
    String? search,
    String? outletId,
    required DateTime dateFrom,
    required DateTime dateTo,
  }) async {
    try {
      final resolvedOutletId =
          outletId ?? _outletLocalDataProvider.getSelectedOutletId();

      final result = await _dataProvider.fetch(
        page: page,
        limit: limit,
        status: status,
        search: search,
        outletId: resolvedOutletId,
        dateFrom: dateFrom,
        dateTo: dateTo,
      );

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

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

      return right(orders);
    } catch (e, s) {
      log('getOrderError', name: _logName, error: e, stackTrace: s);
      return left(const OrderFailure.unexpectedError());
    }
  }
}
