import 'package:drift_dev/api/migrations_native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/db/database.dart';

import 'schema/schema.dart';

void main() {
  late SchemaVerifier verifier;

  setUpAll(() {
    verifier = SchemaVerifier(GeneratedHelper());
  });

  test('freshly created database matches the exported schema v8', () async {
    final schema = await verifier.schemaAt(8);
    final db = AppDatabase(schema.newConnection());
    await verifier.migrateAndValidate(db, 8);
    await db.close();
  });

  test('upgrades v1 → v8 (Lot.type, harvestMonth, presentation, '
      'Attachment.sortOrder, Variety.isDraft/isOrganic, Species.viabilityYears, '
      'v8 provenance/calendar/abundance/condition-checks) and matches the fresh '
      'schema', () async {
    final connection = await verifier.startAt(1);
    final db = AppDatabase(connection);
    await verifier.migrateAndValidate(db, 8);
    await db.close();
  });

  test('upgrades v2 → v8 and matches the fresh schema', () async {
    final connection = await verifier.startAt(2);
    final db = AppDatabase(connection);
    await verifier.migrateAndValidate(db, 8);
    await db.close();
  });

  test('upgrades v3 → v8 and matches the fresh schema', () async {
    final connection = await verifier.startAt(3);
    final db = AppDatabase(connection);
    await verifier.migrateAndValidate(db, 8);
    await db.close();
  });

  test('upgrades v4 → v8 and matches the fresh schema', () async {
    final connection = await verifier.startAt(4);
    final db = AppDatabase(connection);
    await verifier.migrateAndValidate(db, 8);
    await db.close();
  });

  test(
    'upgrades v5 → v8 (adds Variety.isDraft) and matches the fresh schema',
    () async {
      final connection = await verifier.startAt(5);
      final db = AppDatabase(connection);
      await verifier.migrateAndValidate(db, 8);
      await db.close();
    },
  );

  test('upgrades v6 → v8 (adds Variety.isOrganic, Species.viabilityYears) and '
      'matches the fresh schema', () async {
    final connection = await verifier.startAt(6);
    final db = AppDatabase(connection);
    await verifier.migrateAndValidate(db, 8);
    await db.close();
  });

  test('upgrades v7 → v8 (adds Variety.needsReproduction + crop calendar, '
      'Lot.origin/abundance/preservationFormat, ConditionChecks) and matches '
      'the fresh schema', () async {
    final connection = await verifier.startAt(7);
    final db = AppDatabase(connection);
    await verifier.migrateAndValidate(db, 8);
    await db.close();
  });
}
