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('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,
    Map<String, String>? readSeed,
  }) : _data = {...?readSeed};

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

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

  @override
  void remove(String key) {
    _data.remove(key);
  }

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