import 'package:drift/native.dart';
import 'package:scheduler_core/scheduler_core.dart' as core;
import 'package:scheduler_persistence_sqlite/sqlite.dart';
import 'package:test/test.dart';

import '../../scheduler_persistence/test/repo_conformance.dart';

void main() {
  runRepositoryComplianceTests(
    RepositoryComplianceFactories(
      taskRepository: () => _repo(SqliteTaskRepository.new),
      projectRepository: () => _repo(SqliteProjectRepository.new),
      lockedBlockRepository: () => _repo(SqliteLockedBlockRepository.new),
      settingsRepository: () => _repo(SqliteSettingsRepository.new),
      scheduleSnapshotRepository: () =>
          _repo(SqliteScheduleSnapshotRepository.new),
    ),
  );

  test('average task write latency stays below 50ms', () async {
    final db = SchedulerDb(NativeDatabase.memory());
    addTearDown(db.close);
    final repo = SqliteTaskRepository(db);
    final ownerId = core.OwnerId('latency-owner');
    const writes = 50;
    final stopwatch = Stopwatch()..start();

    for (var index = 0; index < writes; index += 1) {
      final result = await repo.insert(
        ownerId: ownerId,
        task: core.Task(
          id: 'task-$index',
          title: 'Task $index',
          projectId: 'project-a',
          type: core.TaskType.flexible,
          status: core.TaskStatus.backlog,
          durationMinutes: 30,
          createdAt: DateTime.utc(2026, 1, 1),
          updatedAt: DateTime.utc(2026, 1, 1),
        ),
      );
      expect(result.isRight, isTrue);
    }

    stopwatch.stop();
    final averageWriteMs = stopwatch.elapsedMicroseconds /
        Duration.microsecondsPerMillisecond /
        writes;
    expect(averageWriteMs, lessThanOrEqualTo(50));
  });
}

T _repo<T>(T Function(SchedulerDb db) create) {
  final db = SchedulerDb(NativeDatabase.memory());
  addTearDown(db.close);
  return create(db);
}
