import 'dart:developer';

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

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

@Injectable(as: IUserRepository)
class UserRepository implements IUserRepository {
  final UserRemoteDataProvider _dataProvider;
  final AuthLocalDataProvider _authLocalDataProvider;

  final String _logName = 'UserRepository';

  UserRepository(this._dataProvider, this._authLocalDataProvider);

  @override
  Future<Either<UserFailure, User>> editUser({required String name}) async {
    try {
      User currentUser = await _authLocalDataProvider.currentUser();
      final result = await _dataProvider.updateUser(
        name: name,
        userId: currentUser.id,
      );

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

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

      await _authLocalDataProvider.saveCurrentUser(result.data!);

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

  @override
  Future<Either<UserFailure, Unit>> changePassword({
    required String newPassword,
    required String currentPassword,
  }) async {
    try {
      User currentUser = await _authLocalDataProvider.currentUser();
      final result = await _dataProvider.changePassword(
        newPassword: newPassword,
        currentPassword: currentPassword,
        userId: currentUser.id,
      );

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

      return right(unit);
    } catch (e, s) {
      log('changePasswordError', name: _logName, error: e, stackTrace: s);
      return left(const UserFailure.unexpectedError());
    }
  }
}
