import 'dart:io';

import 'package:commons_core/commons_core.dart';
import 'package:drift/native.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';

/// Proves the "reopen and it's still there" half of the sprint's definition of
/// done at the persistence layer, on a real on-disk file (unencrypted here so
/// it runs on any host — encryption at rest is covered by no_plaintext_test).
void main() {
  test('a seed survives closing and reopening the database file', () async {
    final dir = await Directory.systemTemp.createTemp('tane_persist');
    addTearDown(() => dir.delete(recursive: true));
    final file = File(p.join(dir.path, 'inventory.sqlite'));

    var db = AppDatabase(NativeDatabase(file));
    await VarietyRepository(
      db,
      idGen: IdGen(),
      nodeId: 'n',
    ).addQuickVariety(label: 'Persisted tomato');
    await db.close();

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

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