import 'dart:developer';

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

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

@Injectable(as: IAuthRepository)
class AuthRepository implements IAuthRepository {
  final AuthLocalDataProvider _localDataProvider;
  final AuthRemoteDataProvider _remoteDataProvider;

  final String _logName = 'AuthRepository';

  AuthRepository(this._localDataProvider, this._remoteDataProvider);

  @override
  Future<Either<AuthFailure, Auth>> login({
    required String email,
    required String password,
    required String deviceId,
    required String deviceName,
    required String deviceType,
    required String platform,
    required String osVersion,
    required String appVersion,
    String? fcmToken,
  }) async {
    try {
      final result = await _remoteDataProvider.login(
        email: email,
        password: password,
        deviceId: deviceId,
        deviceName: deviceName,
        deviceType: deviceType,
        platform: platform,
        osVersion: osVersion,
        appVersion: appVersion,
        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 _remoteDataProvider.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());
    }
  }
}
