import 'dart:developer';

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

import '../../../domain/outlet/outlet.dart';
import '../../auth/datasources/local_data_provider.dart';
import '../datasource/remote_data_provider.dart';

@Injectable(as: IOutletRepository)
class OutletRepository implements IOutletRepository {
  final OutletRemoteDataProvider _dataProvider;
  final AuthLocalDataProvider _authLocalDataProvider;
  final String _logName = 'OutletRepository';

  OutletRepository(this._dataProvider, this._authLocalDataProvider);

  @override
  Future<Either<OutletFailure, Outlet>> currentOutlet() async {
    try {
      final authData = await _authLocalDataProvider.currentUser();
      final result = await _dataProvider.fetchById(outletId: authData.outletId);

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

      final auth = result.data!.toDomain();

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

  @override
  Future<Either<OutletFailure, List<Outlet>>> getList({
    int page = 1,
    int limit = 10,
    String? search,
    bool? isActive,
  }) async {
    try {
      final result = await _dataProvider.fetchList(
        page: page,
        limit: limit,
        search: search,
        isActive: isActive,
      );

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

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

      return right(outlets);
    } catch (e, s) {
      log('getOutletListError', name: _logName, error: e, stackTrace: s);
      return left(const OutletFailure.unexpectedError());
    }
  }
}
