import 'package:commons_core/commons_core.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/services/inventory_snapshot_io.dart';
import 'package:tane/services/social_connection.dart';
import 'package:tane/services/social_service.dart';
import 'package:tane/services/social_settings.dart';
import 'package:tane/services/sync_service.dart';

import '../support/test_support.dart';

/// Records what it's asked to build/apply — no DB, no relay.
class _FakeIO implements InventorySnapshotIO {
  final applied = <List<int>>[];
  List<int> snapshot = const [1, 2, 3];

  @override
  Future<List<int>> buildSnapshot() async => snapshot;

  @override
  Future<void> applySnapshot(List<int> bytes) async => applied.add(bytes);
}

void main() {
  const seedHex =
      '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f';

  Future<SyncService> make(_FakeIO io) async => SyncService(
        connection: SocialConnection(
          social: await SocialService.fromRootSeedHex(seedHex),
          settings: SocialSettings(InMemorySecretStore()),
          open: (_) async => throw StateError('unused'),
          online: const Stream.empty(),
        ),
        io: io,
        localChanges: const Stream.empty(),
        selfDeviceId: 'me',
      );

  SyncSnapshot snap(String device, List<int> data) =>
      SyncSnapshot(deviceId: device, data: data, at: DateTime(2026));

  test('merges another device\'s snapshot into the local inventory', () async {
    final io = _FakeIO();
    final sync = await make(io);
    await sync.handleRemote(snap('other', const [9, 9, 9]));
    expect(io.applied, [
      [9, 9, 9]
    ]);
    await sync.stop();
  });

  test('ignores our own device\'s snapshot (no self-echo)', () async {
    final io = _FakeIO();
    final sync = await make(io);
    await sync.handleRemote(snap('me', const [1]));
    expect(io.applied, isEmpty);
    await sync.stop();
  });
}
