import 'dart:developer';

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

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

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

  final String _logName = 'AuthRepository';

  AuthRepository(this._remoteDataProvider);

  @override
  Future<Either<AuthFailure, CheckPhone>> checkPhone({
    required String phoneNumber,
  }) async {
    try {
      final result = await _remoteDataProvider.checkPhone(
        phoneNumber: phoneNumber,
      );

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

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

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

  @override
  Future<Either<AuthFailure, Register>> register({
    required String phoneNumber,
    required String name,
    required DateTime birthDate,
  }) async {
    try {
      final result = await _remoteDataProvider.register(
        phoneNumber: phoneNumber,
        name: name,
        birthDate: birthDate,
      );

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

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

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