import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
import 'package:mocktail/mocktail.dart';
import 'package:rasadyar_core/core.dart';

class MockHiveBox extends Mock implements Box {}

void main() {
  group('TokenStorageService Tests', () {
    late TokenStorageService tokenStorageService;
    late MockHiveBox mockBox;

    setUp(() {
      mockBox = MockHiveBox();
      tokenStorageService = TokenStorageService();

      // Setup Hive mock
      when(() => mockBox.get(any())).thenReturn(null);
      when(() => mockBox.put(any(), any())).thenAnswer((_) async {});
      when(() => mockBox.delete(any())).thenAnswer((_) async {});
      when(() => mockBox.clear()).thenAnswer((_) async {});
    });

    tearDown(() {
      Get.reset();
    });

    test('should initialize correctly', () async {
      // Act
      await tokenStorageService.init();

      // Assert
      expect(tokenStorageService, isA<TokenStorageService>());
    });

    test('should save and retrieve access token', () {
      // Arrange
      const testToken = 'test_access_token';
      when(() => mockBox.get('accessToken')).thenReturn(testToken);

      // Act
      tokenStorageService.saveAccessToken(testToken);
      final retrievedToken = tokenStorageService.getAccessToken();

      // Assert
      expect(retrievedToken, equals(testToken));
    });

    test('should save and retrieve refresh token', () {
      // Arrange
      const testToken = 'test_refresh_token';
      when(() => mockBox.get('refreshToken')).thenReturn(testToken);

      // Act
      tokenStorageService.saveRefreshToken(testToken);
      final retrievedToken = tokenStorageService.getRefreshToken();

      // Assert
      expect(retrievedToken, equals(testToken));
    });

    test('should clear all tokens', () {
      // Act
      tokenStorageService.clearTokens();

      // Assert
      expect(tokenStorageService.getAccessToken(), isNull);
      expect(tokenStorageService.getRefreshToken(), isNull);
    });

    test('should check if user is authenticated', () {
      // Arrange
      when(() => mockBox.get('accessToken')).thenReturn('valid_token');

      // Act
      final isAuthenticated = tokenStorageService.isAuthenticated();

      // Assert
      expect(isAuthenticated, isTrue);
    });

    test('should return false when not authenticated', () {
      // Arrange
      when(() => mockBox.get('accessToken')).thenReturn(null);

      // Act
      final isAuthenticated = tokenStorageService.isAuthenticated();

      // Assert
      expect(isAuthenticated, isFalse);
    });

    test('should handle empty token strings', () {
      // Arrange
      when(() => mockBox.get('accessToken')).thenReturn('');

      // Act
      final isAuthenticated = tokenStorageService.isAuthenticated();

      // Assert
      expect(isAuthenticated, isFalse);
    });
  });
}
