import 'package:flutter_test/flutter_test.dart';
import 'package:userfront/core/services/auth_token_store_backend.dart';

void main() {
  group('AuthTokenStoreBackend', () {
    test('local 저장소가 실패하면 session 저장소에서 토큰을 읽는다', () {
      final local = _FakeTarget(throwsOnRead: true);
      final session = _FakeTarget(
        readSeed: {'baron_auth_token': 'session-jwt'},
      );
      final store = AuthTokenStoreBackend(
        localTarget: local,
        sessionTarget: session,
      );

      expect(store.getToken(), 'session-jwt');
    });

    test('local 저장소가 실패하면 session 저장소에 토큰을 저장한다', () {
      final local = _FakeTarget(throwsOnWrite: true);
      final session = _FakeTarget();
      final store = AuthTokenStoreBackend(
        localTarget: local,
        sessionTarget: session,
      );

      store.setToken('new-token', provider: 'ory');

      expect(session.read('baron_auth_token'), 'new-token');
      expect(session.read('baron_auth_provider'), 'ory');
    });

    test('cookie mode는 token을 제거하고 provider를 유지한다', () {
      final local = _FakeTarget();
      final session = _FakeTarget();
      final store = AuthTokenStoreBackend(
        localTarget: local,
        sessionTarget: session,
      );

      store.setToken('jwt-token', provider: 'ory');
      store.setCookieMode(provider: 'cookie-provider');

      expect(store.getToken(), isNull);
      expect(store.usesCookie(), isTrue);
      expect(store.getProvider(), 'cookie-provider');
      expect(local.read('baron_auth_cookie_mode'), '1');
      expect(session.read('baron_auth_token'), isNull);
    });

    test('pending provider는 빈 값이면 제거하고 저장소 오류는 건너뛴다', () {
      final local = _FakeTarget(throwsOnWrite: true, throwsOnRemove: true);
      final session = _FakeTarget();
      final store = AuthTokenStoreBackend(
        localTarget: local,
        sessionTarget: session,
      );

      store.setPendingProvider('ory');
      expect(store.getPendingProvider(), 'ory');
      expect(session.read('baron_auth_pending_provider'), 'ory');

      store.setPendingProvider('');
      expect(store.getPendingProvider(), isNull);
      expect(session.read('baron_auth_pending_provider'), isNull);
    });

    test('local/session 저장이 모두 실패해도 memory fallback으로 읽을 수 있다', () {
      final store = AuthTokenStoreBackend(
        localTarget: _FakeTarget(throwsOnWrite: true, throwsOnRead: true),
        sessionTarget: _FakeTarget(throwsOnWrite: true, throwsOnRead: true),
      );

      store.setToken('memory-token');
      store.setPendingProvider('memory-provider');

      expect(store.getToken(), 'memory-token');
      expect(store.getPendingProvider(), 'memory-provider');
    });

    test('clear 호출 시 local/session/memory 모두 정리된다', () {
      final local = _FakeTarget(
        readSeed: {
          'baron_auth_token': 'local-token',
          'baron_auth_provider': 'ory',
        },
      );
      final session = _FakeTarget(
        readSeed: {
          'baron_auth_token': 'session-token',
          'baron_auth_provider': 'ory',
          'baron_auth_cookie_mode': '1',
        },
      );
      final store = AuthTokenStoreBackend(
        localTarget: local,
        sessionTarget: session,
      );

      store.clear();

      expect(local.read('baron_auth_token'), isNull);
      expect(local.read('baron_auth_provider'), isNull);
      expect(session.read('baron_auth_token'), isNull);
      expect(session.read('baron_auth_provider'), isNull);
      expect(session.read('baron_auth_cookie_mode'), isNull);
      expect(store.getToken(), isNull);
      expect(store.getProvider(), isNull);
      expect(store.usesCookie(), isFalse);
    });
  });
}

class _FakeTarget implements AuthTokenStorageTarget {
  _FakeTarget({
    this.throwsOnRead = false,
    this.throwsOnWrite = false,
    this.throwsOnRemove = false,
    Map<String, String>? readSeed,
  }) : _data = {...?readSeed};

  final bool throwsOnRead;
  final bool throwsOnWrite;
  final bool throwsOnRemove;
  final Map<String, String> _data;

  @override
  String? read(String key) {
    if (throwsOnRead) {
      throw Exception('read failed');
    }
    return _data[key];
  }

  @override
  void remove(String key) {
    if (throwsOnRemove) {
      throw Exception('remove failed');
    }
    _data.remove(key);
  }

  @override
  void write(String key, String value) {
    if (throwsOnWrite) {
      throw Exception('write failed');
    }
    _data[key] = value;
  }
}
