import 'package:dartz/dartz.dart';
import 'package:injectable/injectable.dart';
import 'package:superport/core/errors/failures.dart';
import 'package:superport/core/services/lookups_service.dart';
import 'package:superport/data/datasources/remote/lookup_remote_datasource.dart';
import 'package:superport/data/models/lookups/lookup_data.dart';
import 'package:superport/domain/repositories/lookups_repository.dart';

/// Lookups Repository 구현체 (Data Layer)
@LazySingleton(as: LookupsRepository)
class LookupsRepositoryImpl implements LookupsRepository {
  final LookupRemoteDataSource _remoteDataSource;
  final LookupsService _lookupsService;

  LookupsRepositoryImpl(
    this._remoteDataSource,
    this._lookupsService,
  );

  @override
  Future<Either<Failure, LookupData>> getAllLookups() async {
    try {
      // 캐시 서비스가 초기화되지 않았으면 초기화
      if (!_lookupsService.isInitialized) {
        final initResult = await _lookupsService.initialize();
        if (initResult.isLeft()) {
          // 초기화 실패 시 직접 API 호출
          return await _remoteDataSource.getAllLookups();
        }
      }
      
      // 캐시된 데이터 사용
      return _lookupsService.getAllLookups();
    } catch (e) {
      // 캐시 서비스 실패 시 직접 API 호출
      return await _remoteDataSource.getAllLookups();
    }
  }

  @override
  Future<Either<Failure, LookupData>> getLookupsByType(String type) async {
    return await _remoteDataSource.getLookupsByType(type);
  }

  @override
  Either<Failure, LookupData> getCachedLookups() {
    return _lookupsService.getAllLookups();
  }

  @override
  Future<Either<Failure, bool>> refreshCache() async {
    return await _lookupsService.refresh();
  }

  @override
  bool isInitialized() {
    return _lookupsService.isInitialized;
  }
}