import 'package:logging/logging.dart';

import 'package:pshared/api/requests/confirmations/login_confirmation.dart';
import 'package:pshared/api/responses/login.dart';
import 'package:pshared/data/mapper/session_identifier.dart';
import 'package:pshared/models/account/account.dart';
import 'package:pshared/data/mapper/account/account.dart';
import 'package:pshared/api/responses/confirmation.dart';
import 'package:pshared/models/auth/pending_login.dart';
import 'package:pshared/service/authorization/storage.dart';
import 'package:pshared/service/services.dart';
import 'package:pshared/utils/http/requests.dart';


class VerificationService {
  static final _logger = Logger('service.verification');
  static const String _objectType = Services.confirmations;

  static Future<ConfirmationResponse> requestLoginCode(PendingLogin pending, {String? destination}) async {
    _logger.fine('Requesting login confirmation code');
    final response = await getPOSTResponse(
      _objectType,
      '',
      LoginConfirmationRequest(destination: destination).toJson(),
      authToken: pending.pendingToken.token,
    );
    return ConfirmationResponse.fromJson(response);
  }

  static Future<ConfirmationResponse> resendLoginCode(PendingLogin pending, {String? destination}) async {
    _logger.fine('Resending login confirmation code');
    final response = await getPOSTResponse(
      _objectType,
      '/resend',
      LoginConfirmationRequest(destination: destination).toJson(),
      authToken: pending.pendingToken.token,
    );
    return ConfirmationResponse.fromJson(response);
  }

  static Future<Account> confirmLoginCode({
    required PendingLogin pending,
    required String code,
    String? destination,
  }) async {
    _logger.fine('Confirming login code');
    final response = await getPOSTResponse(
      _objectType,
      '/verify',
      LoginConfirmationVerifyRequest(
        code: code,
        destination: destination,
        sessionIdentifier: pending.session.toDTO(),
      ).toJson(),
      authToken: pending.pendingToken.token,
    );

    final loginResponse = LoginResponse.fromJson(response);
    await AuthorizationStorage.updateToken(loginResponse.accessToken);
    await AuthorizationStorage.updateRefreshToken(loginResponse.refreshToken);
    return loginResponse.account.toDomain();
  }
}
