import '../notifiers/auth_notifier.dart';
import 'auth_proxy_service.dart';
import 'auth_token_store.dart';

typedef CurrentSessionLoader = Future<String?> Function();
typedef SessionRevoker = Future<void> Function(String sessionId);
typedef LogoutCallback = void Function();

class LogoutService {
  LogoutService({
    CurrentSessionLoader? loadCurrentSessionId,
    SessionRevoker? revokeSession,
    LogoutCallback? clearAuth,
    LogoutCallback? notifyAuthChanged,
  }) : _loadCurrentSessionId =
           loadCurrentSessionId ?? AuthProxyService.fetchCurrentSessionId,
       _revokeSession = revokeSession ?? AuthProxyService.revokeSession,
       _clearAuth = clearAuth ?? AuthTokenStore.clear,
       _notifyAuthChanged = notifyAuthChanged ?? AuthNotifier.instance.notify;

  final CurrentSessionLoader _loadCurrentSessionId;
  final SessionRevoker _revokeSession;
  final LogoutCallback _clearAuth;
  final LogoutCallback _notifyAuthChanged;

  Future<void> logout() async {
    try {
      final currentSessionId = await _loadCurrentSessionId();
      if (currentSessionId != null && currentSessionId.isNotEmpty) {
        await _revokeSession(currentSessionId);
      }
    } catch (_) {
      // 서버 세션 종료는 best-effort로 처리하고, 로컬 로그아웃은 계속 진행합니다.
    } finally {
      _clearAuth();
      _notifyAuthChanged();
    }
  }
}
