import 'dart:developer';

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

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

@Injectable(as: IAuthRepository)
class AuthRepository implements IAuthRepository {
  final AuthRemoteDataProvider _dataProvider;
  final AuthLocalDataProvider _localDataProvider;
  final String _logName = 'AuthRepository';

  AuthRepository(this._dataProvider, this._localDataProvider);

  @override
  Future<Either<AuthFailure, Login>> login({
    required String email,
    required String password,
    required Map<String, String> devicePayload,
    required String fcmToken,
  }) async {
    try {
      final result = await _dataProvider.login(
        email: email,
        password: password,
        devicePayload: devicePayload,
        fcmToken: fcmToken,
      );

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

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

      await _localDataProvider.saveToken(auth.token);
      await _localDataProvider.saveCurrentUser(result.data!.user!);

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

  @override
  Future<Either<AuthFailure, User>> currentUser() async {
    try {
      User user = await _localDataProvider.currentUser();
      return right(user);
    } catch (e, s) {
      log('currentUserError', name: _logName, error: e, stackTrace: s);
      return left(const AuthFailure.unexpectedError());
    }
  }

  @override
  Future<bool> hasToken() async {
    return await _localDataProvider.hasToken();
  }

  @override
  Future<Either<AuthFailure, Unit>> logout() async {
    try {
      final result = await _dataProvider.logout();

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

      await _localDataProvider.deleteAllAuth();
      return right(unit);
    } catch (e, s) {
      log('logoutError', name: _logName, error: e, stackTrace: s);
      return left(const AuthFailure.unexpectedError());
    }
  }
}
