// SPDX-FileCopyrightText: 2026 FocusFlow contributors
// SPDX-License-Identifier: AGPL-3.0-only

/// Tests Sqlite Repository Conformance behavior for the Scheduler Persistence Sqlite package.
library;

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';

/// Entry point for this executable Dart file.
/// It wires the local command, test, or application behavior needed by this repository without exposing additional public API.
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));
  });
}

/// Top-level helper that performs the `_repo<T>` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
T _repo<T>(T Function(SchedulerDb db) create) {
  final db = SchedulerDb(NativeDatabase.memory());
  addTearDown(db.close);
  return create(db);
}
