import 'package:cargocalculaterapp/core/error/failure.dart';
import 'package:cargocalculaterapp/features/profile/data/models/delete_account_response.dart';
import 'package:cargocalculaterapp/features/profile/data/models/profile_update_request.dart';
import 'package:cargocalculaterapp/features/profile/domain/repository/profile_repository.dart';
import 'package:dartz/dartz.dart';
import '../../../../constants/constants.dart';
import '../../../../core/error/exceptions.dart';
import '../data_source/local/profile_local_data_source.dart';
import '../data_source/remote/profile_remote_data_source.dart';
import '../models/profile_response.dart';

class ProfileRepositoryImpl extends ProfileRepository {
  final ProfileRemoteDataSource remoteDataSource;
  final ProfileLocalDataSource localDataSource;

  ProfileRepositoryImpl(this.remoteDataSource, this.localDataSource);

  @override
  Future<Either<Failure, ProfileResponse>> getProfile(bool isCache) async {
    if (!isCache) {
      try {
        final response = await remoteDataSource.getProfile();
        localDataSource.setProfile(response);
        return Right(response);
      } catch (e) {
        return Left(ServerFailure(message: e.toString()));
      }
    } else {
      try {
        final response = await localDataSource.getProfile();
        return Right(response);
      } catch (e) {
        return Left(
          CacheFailure(
            message: (e is CacheException)
                ? e.message
                : Warnings.someThingWentWrong,
          ),
        );
      }
    }
  }

  @override
  Future<Either<Failure, ProfileResponse>> updateProfile(
    ProfileUpdateRequest request,
  ) async {
    try {
      final response = await remoteDataSource.updateProfile(request);
      localDataSource.setProfile(response);
      return Right(response);
    } catch (e) {
      return Left(ServerFailure(message: e.toString()));
    }
  }

  @override
  Future<Either<Failure, DeleteAccountResponse>> deleteProfile() async {
    try {
      final response = await remoteDataSource.deleteProfile();
      return Right(response);
    } catch (e) {
      return Left(ServerFailure(message: e.toString()));
    }
  }
}
