import 'package:social_app/core/storage/token_storage.dart';
import 'auth_api.dart';
import 'auth_repository.dart';
import 'models/signup_request.dart';
import 'models/login_request.dart';
import 'models/auth_response.dart';

class AuthRepositoryImpl implements AuthRepository {
  final AuthApi _api;
  final TokenStorage _tokenStorage;

  AuthRepositoryImpl({required AuthApi api, required TokenStorage tokenStorage})
    : _api = api,
      _tokenStorage = tokenStorage;

  @override
  Future<VerificationCreateResponse> createVerification(
    SignupStartRequest request,
  ) {
    return _api.createVerification(request);
  }

  @override
  Future<AuthResponse> verifyVerification(SignupVerifyRequest request) async {
    final response = await _api.verifyVerification(request);
    await _tokenStorage.saveTokens(
      access: response.accessToken,
      refresh: response.refreshToken,
    );
    return response;
  }

  @override
  Future<void> resendVerification(SignupResendRequest request) {
    return _api.resendVerification(request);
  }

  @override
  Future<AuthResponse> createSession(LoginRequest request) async {
    final response = await _api.createSession(request);
    await _tokenStorage.saveTokens(
      access: response.accessToken,
      refresh: response.refreshToken,
    );
    return response;
  }

  @override
  Future<AuthResponse> refreshSession(String refreshToken) async {
    final response = await _api.refreshSession(
      RefreshRequest(refreshToken: refreshToken),
    );
    await _tokenStorage.saveTokens(
      access: response.accessToken,
      refresh: response.refreshToken,
    );
    return response;
  }

  @override
  Future<void> deleteSession() async {
    final refreshToken = await _tokenStorage.getRefreshToken();
    if (refreshToken != null) {
      await _api.deleteSession(LogoutRequest(refreshToken: refreshToken));
    }
    await _tokenStorage.clear();
  }

  @override
  Future<String?> getAccessToken() => _tokenStorage.getAccessToken();

  @override
  Future<String?> getRefreshToken() => _tokenStorage.getRefreshToken();

  @override
  Future<bool> isAuthenticated() async {
    final token = await _tokenStorage.getAccessToken();
    return token != null;
  }

  @override
  Future<void> requestPasswordReset(String email) {
    return _api.requestPasswordReset(email);
  }

  @override
  Future<void> confirmPasswordReset({
    required String email,
    required String token,
    required String newPassword,
  }) {
    return _api.confirmPasswordReset(
      email: email,
      token: token,
      newPassword: newPassword,
    );
  }
}
