import 'dart:io';

import 'package:commons_core/commons_core.dart';
import 'package:integration_test/integration_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:tane/data/variety_repository.dart';
import 'package:tane/db/database.dart';
import 'package:tane/db/encrypted_executor.dart';

/// On-device end-to-end: a seed added to the *encrypted* database survives a
/// close and reopen. Runs where SQLCipher is available (device / CI with the
/// library); skips with a clear reason otherwise.
void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  testWidgets('a seed persists in the encrypted DB across reopen', (
    tester,
  ) async {
    const keyHex =
        '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff';
    final dir = await Directory.systemTemp.createTemp('tane_e2e');
    addTearDown(() => dir.delete(recursive: true));
    final file = File(p.join(dir.path, 'inventory.sqlite'));

    var db = AppDatabase(openEncryptedExecutor(file, keyHex));
    try {
      await VarietyRepository(
        db,
        idGen: IdGen(),
        nodeId: 'n',
      ).addQuickVariety(label: 'Persisted tomato');
    } on Object catch (e) {
      markTestSkipped('SQLCipher unavailable: $e');
      await db.close();
      return;
    }
    await db.close();

    db = AppDatabase(openEncryptedExecutor(file, keyHex));
    final items = await VarietyRepository(
      db,
      idGen: IdGen(),
      nodeId: 'n',
    ).watchInventory().first;
    await db.close();

    expect(items.map((i) => i.label), contains('Persisted tomato'));
  });
}
