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

part of '../../../../application_layer.dart';

/// Private implementation type for `_UnitOfWorkTaskRepository` in this library.
/// It keeps supporting state and behavior scoped to the owning file so the public API stays focused on the scheduler concepts that callers use directly.
class _UnitOfWorkTaskRepository implements TaskRepository {
  /// Creates a `_UnitOfWorkTaskRepository` instance with the values required by its invariants.
  /// Callers should pass already-normalized scheduler data because validation and defaulting belong at the model or service boundary, not in arbitrary UI code.
  _UnitOfWorkTaskRepository({
    required Map<String, Task> tasksById,
    required Map<String, String> ownersById,
    required Map<String, int> revisionsById,
  })  : _tasksById = tasksById,
        _ownersById = ownersById,
        _revisionsById = revisionsById;

  /// Private state stored as `_tasksById` for this implementation.
  /// The field is intentionally scoped to this library so only the owning type can change the related scheduler or UI behavior.
  final Map<String, Task> _tasksById;

  /// Private state stored as `_ownersById` for this implementation.
  /// The field is intentionally scoped to this library so only the owning type can change the related scheduler or UI behavior.
  final Map<String, String> _ownersById;

  /// Private state stored as `_revisionsById` for this implementation.
  /// The field is intentionally scoped to this library so only the owning type can change the related scheduler or UI behavior.
  final Map<String, int> _revisionsById;

  /// Runs the `findById` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<Task?> findById(String id) async => _tasksById[id];

  /// Runs the `findRecordById` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<RepositoryRecord<Task>?> findRecordById(String id) async {
    final task = _tasksById[id];
    if (task == null) {
      return null;
    }
    return RepositoryRecord(
      value: task,
      ownerId: _ownerFor(id),
      revision: _revisionFor(id),
    );
  }

  /// Runs the `findAll` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<List<Task>> findAll() async {
    return List<Task>.unmodifiable(_tasksById.values);
  }

  /// Runs the `findByStatus` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<List<Task>> findByStatus(TaskStatus status) async {
    return List<Task>.unmodifiable(
      _tasksById.values.where((task) => task.status == status),
    );
  }

  /// Runs the `findByOwner` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<RepositoryPage<Task>> findByOwner({
    required String ownerId,
    RepositoryPageRequest page = const RepositoryPageRequest(),
  }) async {
    final tasks = _tasksById.values
        .where((task) => _ownerFor(task.id) == ownerId)
        .toList(growable: false)
      ..sort(_compareTaskIds);
    return _page(tasks, page);
  }

  /// Runs the `findByProjectId` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<RepositoryPage<Task>> findByProjectId({
    required String ownerId,
    required String projectId,
    RepositoryPageRequest page = const RepositoryPageRequest(),
  }) async {
    final tasks = _tasksById.values
        .where(
          (task) =>
              _ownerFor(task.id) == ownerId && task.projectId == projectId,
        )
        .toList(growable: false)
      ..sort(_compareTaskIds);
    return _page(tasks, page);
  }

  /// Runs the `findByParentTaskId` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<RepositoryPage<Task>> findByParentTaskId({
    required String ownerId,
    required String parentTaskId,
    RepositoryPageRequest page = const RepositoryPageRequest(),
  }) async {
    final tasks = _tasksById.values
        .where(
          (task) =>
              _ownerFor(task.id) == ownerId &&
              task.parentTaskId == parentTaskId,
        )
        .toList(growable: false)
      ..sort(_compareTaskIds);
    return _page(tasks, page);
  }

  /// Runs the `findBacklogCandidates` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<RepositoryPage<Task>> findBacklogCandidates(
    BacklogCandidateQuery query,
  ) async {
    final tasks = _tasksById.values
        .where(
          (task) =>
              _ownerFor(task.id) == query.ownerId &&
              task.status == TaskStatus.backlog &&
              (query.projectId == null || task.projectId == query.projectId) &&
              query.tags.every(task.backlogTags.contains),
        )
        .toList(growable: false)
      ..sort(_compareBacklogCandidates);
    return _page(tasks, query.page);
  }

  /// Runs the `findScheduledInWindow` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<List<Task>> findScheduledInWindow(SchedulingWindow window) async {
    return List<Task>.unmodifiable(
      _tasksById.values.where((task) {
        return _taskOverlapsWindow(task, window);
      }),
    );
  }

  /// Runs the `findScheduledInWindowForOwner` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<RepositoryPage<Task>> findScheduledInWindowForOwner({
    required String ownerId,
    required SchedulingWindow window,
    RepositoryPageRequest page = const RepositoryPageRequest(),
  }) async {
    final tasks = _tasksById.values
        .where(
          (task) =>
              _ownerFor(task.id) == ownerId &&
              _taskOverlapsWindow(task, window),
        )
        .toList(growable: false)
      ..sort(_compareScheduledTasks);
    return _page(tasks, page);
  }

  /// Runs the `findForLocalDay` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<RepositoryPage<Task>> findForLocalDay({
    required String ownerId,
    required CivilDate localDate,
    required SchedulingWindow window,
    RepositoryPageRequest page = const RepositoryPageRequest(),
  }) {
    return findScheduledInWindowForOwner(
      ownerId: ownerId,
      window: window,
      page: page,
    );
  }

  /// Runs the `save` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<void> save(Task task) async {
    _tasksById[task.id] = task;
    _ownersById.putIfAbsent(task.id, () => 'owner-1');
    _revisionsById[task.id] = _revisionFor(task.id) + 1;
  }

  /// Runs the `saveAll` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<void> saveAll(Iterable<Task> tasks) async {
    for (final task in tasks) {
      await save(task);
    }
  }

  /// Runs the `insert` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<RepositoryMutationResult> insert({
    required Task task,
    required String ownerId,
  }) async {
    if (_tasksById.containsKey(task.id)) {
      return RepositoryMutationResult.failure(
        RepositoryFailure(
          code: RepositoryFailureCode.duplicateId,
          entityId: task.id,
        ),
      );
    }
    _tasksById[task.id] = task;
    _ownersById[task.id] = ownerId;
    _revisionsById[task.id] = 1;
    return RepositoryMutationResult.success(revision: 1);
  }

  /// Runs the `saveIfRevision` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<RepositoryMutationResult> saveIfRevision({
    required Task task,
    required String ownerId,
    required int expectedRevision,
  }) async {
    if (!_tasksById.containsKey(task.id) || _ownerFor(task.id) != ownerId) {
      return RepositoryMutationResult.failure(
        RepositoryFailure(
            code: RepositoryFailureCode.notFound, entityId: task.id),
      );
    }
    final actualRevision = _revisionFor(task.id);
    if (actualRevision != expectedRevision) {
      return RepositoryMutationResult.failure(
        RepositoryFailure(
          code: RepositoryFailureCode.staleRevision,
          entityId: task.id,
          expectedRevision: expectedRevision,
          actualRevision: actualRevision,
        ),
      );
    }
    final nextRevision = actualRevision + 1;
    _tasksById[task.id] = task;
    _ownersById[task.id] = ownerId;
    _revisionsById[task.id] = nextRevision;
    return RepositoryMutationResult.success(revision: nextRevision);
  }

  /// Runs the `deleteIfRevision` operation and completes after its asynchronous work finishes.
  /// Callers should await the returned future so repository writes, UI refreshes, and failure handling happen in a predictable order.
  @override
  Future<RepositoryMutationResult> deleteIfRevision({
    required String taskId,
    required String ownerId,
    required int expectedRevision,
  }) async {
    if (!_tasksById.containsKey(taskId) || _ownerFor(taskId) != ownerId) {
      return RepositoryMutationResult.failure(
        RepositoryFailure(
            code: RepositoryFailureCode.notFound, entityId: taskId),
      );
    }
    final actualRevision = _revisionFor(taskId);
    if (actualRevision != expectedRevision) {
      return RepositoryMutationResult.failure(
        RepositoryFailure(
          code: RepositoryFailureCode.staleRevision,
          entityId: taskId,
          expectedRevision: expectedRevision,
          actualRevision: actualRevision,
        ),
      );
    }
    final nextRevision = actualRevision + 1;
    _tasksById.remove(taskId);
    _ownersById.remove(taskId);
    _revisionsById.remove(taskId);
    return RepositoryMutationResult.success(revision: nextRevision);
  }

  /// Runs the `_ownerFor` helper used inside this library.
  /// The helper centralizes a small piece of transformation or validation so higher-level scheduler flow remains easier to read.
  String _ownerFor(String id) => _ownersById[id] ?? 'owner-1';

  /// Runs the `_revisionFor` helper used inside this library.
  /// The helper centralizes a small piece of transformation or validation so higher-level scheduler flow remains easier to read.
  int _revisionFor(String id) => _revisionsById[id] ?? 1;
}
