import 'package:commons_core/commons_core.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/data/variety_repository.dart';
import 'package:tane/db/database.dart';
import 'package:tane/db/enums.dart';

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

/// A real seed bank can hold thousands of accessions. This guards that the
/// list query stays a handful of batched queries (not N+1) and returns in a
/// human blink even at that scale — the pre-beta performance check.
void main() {
  late AppDatabase db;
  late VarietyRepository repo;

  setUp(() {
    db = newTestDatabase();
    repo = newTestRepository(db);
  });
  tearDown(() => db.close());

  test('the inventory view loads 3000 varieties quickly', () async {
    const count = 3000;
    for (var i = 0; i < count; i++) {
      final id = await repo.addQuickVariety(
        label: 'Variety $i',
        category: i.isEven ? 'Poaceae' : 'Fabaceae',
      );
      // Every few varieties, add a lot so the batched lot/type/share queries
      // do real work.
      if (i % 5 == 0) {
        await repo.addLot(
          varietyId: id,
          harvestYear: 2020 + (i % 5),
          quantity: const Quantity(kind: QuantityKind.handful),
          offerStatus: i % 25 == 0 ? OfferStatus.shared : OfferStatus.private,
        );
      }
    }

    final sw = Stopwatch()..start();
    final view = await repo.watchInventoryView().first;
    sw.stop();

    expect(view.items, hasLength(count));
    // Generous ceiling for CI; typical local runs are well under 500ms. The
    // point is to catch an accidental N+1 regression, not to micro-benchmark.
    expect(
      sw.elapsedMilliseconds,
      lessThan(3000),
      reason: 'inventory view took ${sw.elapsedMilliseconds}ms for $count rows',
    );
  });
}
