import 'package:dartz/dartz.dart';
import '../../../../core/failure.dart';
import '../../../../core/secure_storage.dart';
import '../domain/auth_repository.dart';
import '../domain/user_entity.dart';
import 'auth_remote_data_source.dart';

class AuthRepositoryImpl implements AuthRepository {
  final AuthRemoteDataSource remoteDataSource;
  final SecureStorage secureStorage;

  AuthRepositoryImpl(this.remoteDataSource, this.secureStorage);

  @override
  Future<Either<Failure, UserEntity>> login(String email, String password) async {
    try {
      // 1. Suruh data source nembak API
      final userModel = await remoteDataSource.login(email, password);
      
      // 2. Simpan token langsung ke HP biar UI gausah ribet
      await secureStorage.saveToken(userModel.token);
      
      // 3. Balikin data sukses (Right)
      return Right(userModel);
    } catch (e) {
      // 4. Balikin pesan error (Left)
      return Left(ServerFailure(e.toString().replaceAll('Exception: ', '')));
    }
  }
}