import 'package:dio/dio.dart';
import 'package:dio_smart_retry/dio_smart_retry.dart';
import 'package:injectable/injectable.dart';
import 'package:remever/common/functions.dart';
import 'package:remever/common/resources.dart';
import 'package:remever/common/services/api_client.dart';
import 'package:remever/common/storage.dart';
import 'package:remever/common/typedef.dart';
import 'package:remever/services/auth/auth_interface.dart';

///
/// Сервис авторизации
///

@Singleton(as: AuthInterface)
final class AuthService implements AuthInterface {
  @override
  Future<bool> get isAuth async => await token != null;

  @override
  Future<String?> get token async {
    final String? accessToken = await authSecStorage.read(
      key: StorageKeys.accessToken,
    );

    return accessToken;
  }

  @override
  Future<String?> login(String email) async {
    try {
      final Response<dynamic> result = await apiClient.post(
        '/auth/email/send',
        options: Options()..disableRetry = true,
        data: <String, dynamic>{'email': email.toLowerCase()},
      );

      final Json response = Json.from(result.data);

      if (response['success'] == false) return null;

      return response['result']['authUid'];
    } catch (e, st) {
      logger.logError('Ошибка в методе login', e, st);

      return null;
    }
  }

  @override
  Future<bool> sendCode(String code, String uid) async {
    try {
      final Response<dynamic> result = await apiClient.post(
        '/auth/code/login',
        options: Options()..disableRetry = true,
        data: <String, dynamic>{'authUid': uid, 'confirmCode': code},
      );

      final Json response = Json.from(result.data);

      final bool success = response['success'] ?? false;

      if (success) {
        await authSecStorage.write(
          key: StorageKeys.accessToken,
          value: response['result']['token'],
        );
      }

      return success;
    } catch (e, st) {
      logger.logError('Ошибка в методе send code', e, st);

      return false;
    }
  }
}
