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

part of '../sqlite_repositories.dart';

/// Drift-backed schedule snapshot repository.
final class SqliteScheduleSnapshotRepository
    implements ScheduleSnapshotRepository {
  /// Creates a snapshot repository using [db].
  SqliteScheduleSnapshotRepository(this.db);

  /// Shared SQLite database handle.
  final SchedulerDb db;

  /// 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<RepoResult<core.SchedulingStateSnapshot?>> findById({
    required core.OwnerId ownerId,
    required String snapshotId,
  }) async {
    final row = await _snapshotById(snapshotId);
    if (row == null || row.ownerId != ownerId.value) {
      return const Right(null);
    }
    return Right(_snapshotFromRow(row));
  }

  /// Runs the `findInWindow` 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<RepoResult<core.Page<core.SchedulingStateSnapshot>>> findInWindow({
    required core.OwnerId ownerId,
    required core.SchedulingWindow window,
    core.PageRequest page = const core.PageRequest(),
  }) async {
    final rows = await (db.select(db.snapshots)
          ..where((table) => table.ownerId.equals(ownerId.value))
          ..orderBy([(table) => drift.OrderingTerm.asc(table.id)]))
        .get();
    final matching = rows
        .map(_snapshotFromRow)
        .where((snapshot) => _windowsOverlap(snapshot.window, window))
        .toList(growable: false);
    final offset = _cursorOffset(page.cursor);
    final pageItems = matching.skip(offset).take(page.limit).toList();
    final nextOffset = offset + page.limit;
    return Right(core.Page(
      items: pageItems,
      nextCursor: nextOffset < matching.length ? '$nextOffset' : null,
    ));
  }

  /// 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<RepoResult<core.Revision>> insert({
    required core.OwnerId ownerId,
    required core.SchedulingStateSnapshot snapshot,
  }) async {
    if (await _snapshotById(snapshot.id) != null) {
      return Left(RepositoryDuplicateId(entityId: snapshot.id));
    }
    await db.into(db.snapshots).insert(_snapshotCompanion(
          snapshot,
          ownerId: ownerId,
          revision: core.Revision.initial,
        ));
    return const Right(core.Revision.initial);
  }

  /// Runs the `deleteExpired` 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<RepoResult<int>> deleteExpired({
    required core.OwnerId ownerId,
    required DateTime nowUtc,
  }) async {
    final deleted = await (db.delete(db.snapshots)
          ..where(
            (table) =>
                table.ownerId.equals(ownerId.value) &
                table.retentionExpiresUtc.isSmallerThanValue(nowUtc.toUtc()),
          ))
        .go();
    return Right(deleted);
  }

  /// Runs the `_snapshotById` 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.
  Future<SnapshotRow?> _snapshotById(String id) {
    return (db.select(db.snapshots)..where((table) => table.id.equals(id)))
        .getSingleOrNull();
  }
}

/// Top-level helper that performs the `_taskCompanion` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
TasksCompanion _taskCompanion(
  core.Task task, {
  required core.OwnerId ownerId,
  required core.Revision revision,
}) {
  final doc = core.TaskDocumentMapping.toDocument(
    task,
    ownerId: ownerId.value,
    revision: revision.value,
  );
  return TasksCompanion.insert(
    id: task.id,
    ownerId: ownerId.value,
    title: _string(doc, core.TaskDocumentFields.title),
    projectId: _string(doc, core.TaskDocumentFields.projectId),
    parentId: drift.Value(_nullableString(
      doc,
      core.TaskDocumentFields.parentTaskId,
    )),
    type: _string(doc, core.TaskDocumentFields.type),
    status: _string(doc, core.TaskDocumentFields.status),
    priority: drift.Value(_nullableString(
      doc,
      core.TaskDocumentFields.priority,
    )),
    reward: _string(doc, core.TaskDocumentFields.reward),
    difficulty: _string(doc, core.TaskDocumentFields.difficulty),
    durationMinutes: drift.Value(_nullableInt(
      doc,
      core.TaskDocumentFields.durationMinutes,
    )),
    scheduledStartUtc: drift.Value(_nullableDateTime(
      doc,
      core.TaskDocumentFields.scheduledStart,
    )),
    scheduledEndUtc: drift.Value(_nullableDateTime(
      doc,
      core.TaskDocumentFields.scheduledEnd,
    )),
    actualStartUtc: drift.Value(_nullableDateTime(
      doc,
      core.TaskDocumentFields.actualStart,
    )),
    actualEndUtc: drift.Value(_nullableDateTime(
      doc,
      core.TaskDocumentFields.actualEnd,
    )),
    completedAtUtc: drift.Value(_nullableDateTime(
      doc,
      core.TaskDocumentFields.completedAt,
    )),
    backlogTagsJson: jsonEncode(doc[core.TaskDocumentFields.backlogTags]),
    reminderOverride: drift.Value(_nullableString(
      doc,
      core.TaskDocumentFields.reminderOverride,
    )),
    statsJson: jsonEncode(doc[core.TaskDocumentFields.stats]),
    backlogEnteredAtUtc: drift.Value(_nullableDateTime(
      doc,
      core.TaskDocumentFields.backlogEnteredAt,
    )),
    backlogEnteredProvenance: drift.Value(_nullableString(
      doc,
      core.TaskDocumentFields.backlogEnteredAtProvenance,
    )),
    revision: revision.value,
    createdAtUtc: task.createdAt.toUtc(),
    updatedAtUtc: task.updatedAt.toUtc(),
  );
}

/// Top-level helper that performs the `_taskFromRow` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
core.Task _taskFromRow(TaskRow row) {
  return core.TaskDocumentMapping.fromDocument({
    ..._commonDocumentFields(
        row.id, row.ownerId, row.revision, row.createdAtUtc, row.updatedAtUtc),
    core.TaskDocumentFields.title: row.title,
    core.TaskDocumentFields.projectId: row.projectId,
    core.TaskDocumentFields.type: row.type,
    core.TaskDocumentFields.status: row.status,
    core.TaskDocumentFields.priority: row.priority,
    core.TaskDocumentFields.reward: row.reward,
    core.TaskDocumentFields.difficulty: row.difficulty,
    core.TaskDocumentFields.durationMinutes: row.durationMinutes,
    core.TaskDocumentFields.scheduledStart:
        _storedDateTimeOrNull(row.scheduledStartUtc),
    core.TaskDocumentFields.scheduledEnd:
        _storedDateTimeOrNull(row.scheduledEndUtc),
    core.TaskDocumentFields.actualStart:
        _storedDateTimeOrNull(row.actualStartUtc),
    core.TaskDocumentFields.actualEnd: _storedDateTimeOrNull(row.actualEndUtc),
    core.TaskDocumentFields.completedAt:
        _storedDateTimeOrNull(row.completedAtUtc),
    core.TaskDocumentFields.parentTaskId: row.parentId,
    core.TaskDocumentFields.backlogTags: _jsonList(row.backlogTagsJson),
    core.TaskDocumentFields.reminderOverride: row.reminderOverride,
    core.TaskDocumentFields.stats: _jsonMap(row.statsJson),
    core.TaskDocumentFields.backlogEnteredAt:
        _storedDateTimeOrNull(row.backlogEnteredAtUtc),
    core.TaskDocumentFields.backlogEnteredAtProvenance:
        row.backlogEnteredProvenance,
  });
}

/// Top-level helper that performs the `_projectCompanion` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
ProjectsCompanion _projectCompanion(
  core.ProjectProfile project, {
  required core.OwnerId ownerId,
  required core.Revision revision,
  required DateTime createdAt,
  required DateTime updatedAt,
}) {
  final doc = core.ProjectDocumentMapping.toDocument(
    project,
    ownerId: ownerId.value,
    revision: revision.value,
    createdAt: createdAt,
    updatedAt: updatedAt,
  );
  return ProjectsCompanion.insert(
    id: project.id,
    ownerId: ownerId.value,
    name: _string(doc, core.ProjectDocumentFields.name),
    colorKey: _string(doc, core.ProjectDocumentFields.colorKey),
    defaultPriority: _string(doc, core.ProjectDocumentFields.defaultPriority),
    defaultReward: _string(doc, core.ProjectDocumentFields.defaultReward),
    defaultDifficulty:
        _string(doc, core.ProjectDocumentFields.defaultDifficulty),
    defaultReminderProfile:
        _string(doc, core.ProjectDocumentFields.defaultReminderProfile),
    defaultDurationMinutes: drift.Value(_nullableInt(
      doc,
      core.ProjectDocumentFields.defaultDurationMinutes,
    )),
    archivedAtUtc: drift.Value(_nullableDateTime(
      doc,
      core.ProjectDocumentFields.archivedAt,
    )),
    revision: revision.value,
    createdAtUtc: createdAt.toUtc(),
    updatedAtUtc: updatedAt.toUtc(),
  );
}

/// Top-level helper that performs the `_projectFromRow` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
core.ProjectProfile _projectFromRow(ProjectRow row) {
  return core.ProjectDocumentMapping.fromDocument({
    ..._commonDocumentFields(
        row.id, row.ownerId, row.revision, row.createdAtUtc, row.updatedAtUtc),
    core.ProjectDocumentFields.name: row.name,
    core.ProjectDocumentFields.colorKey: row.colorKey,
    core.ProjectDocumentFields.defaultPriority: row.defaultPriority,
    core.ProjectDocumentFields.defaultReward: row.defaultReward,
    core.ProjectDocumentFields.defaultDifficulty: row.defaultDifficulty,
    core.ProjectDocumentFields.defaultReminderProfile:
        row.defaultReminderProfile,
    core.ProjectDocumentFields.defaultDurationMinutes:
        row.defaultDurationMinutes,
    core.ProjectDocumentFields.archivedAt: _storedDateTimeOrNull(
      row.archivedAtUtc,
    ),
  });
}

/// Top-level helper that performs the `_lockedBlockCompanion` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
LockedBlocksCompanion _lockedBlockCompanion(
  core.LockedBlock block, {
  required core.OwnerId ownerId,
  required core.Revision revision,
}) {
  final doc = core.LockedBlockDocumentMapping.toDocument(
    block,
    ownerId: ownerId.value,
    revision: revision.value,
  );
  return LockedBlocksCompanion.insert(
    id: block.id,
    ownerId: ownerId.value,
    name: _string(doc, core.LockedBlockDocumentFields.name),
    date:
        drift.Value(_nullableString(doc, core.LockedBlockDocumentFields.date)),
    startTime: _string(doc, core.LockedBlockDocumentFields.startTime),
    endTime: _string(doc, core.LockedBlockDocumentFields.endTime),
    recurrenceJson: drift.Value(_jsonEncodeNullable(
      doc[core.LockedBlockDocumentFields.recurrence],
    )),
    hiddenByDefault: _bool(doc, core.LockedBlockDocumentFields.hiddenByDefault),
    projectId: drift.Value(_nullableString(
      doc,
      core.LockedBlockDocumentFields.projectId,
    )),
    archivedAtUtc: drift.Value(_nullableDateTime(
      doc,
      core.LockedBlockDocumentFields.archivedAt,
    )),
    revision: revision.value,
    createdAtUtc: block.createdAt.toUtc(),
    updatedAtUtc: block.updatedAt.toUtc(),
  );
}

/// Top-level helper that performs the `_lockedBlockFromRow` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
core.LockedBlock _lockedBlockFromRow(LockedBlockRow row) {
  return core.LockedBlockDocumentMapping.fromDocument({
    ..._commonDocumentFields(
        row.id, row.ownerId, row.revision, row.createdAtUtc, row.updatedAtUtc),
    core.LockedBlockDocumentFields.name: row.name,
    core.LockedBlockDocumentFields.startTime: row.startTime,
    core.LockedBlockDocumentFields.endTime: row.endTime,
    core.LockedBlockDocumentFields.date: row.date,
    core.LockedBlockDocumentFields.recurrence:
        row.recurrenceJson == null ? null : _jsonMap(row.recurrenceJson!),
    core.LockedBlockDocumentFields.hiddenByDefault: row.hiddenByDefault,
    core.LockedBlockDocumentFields.projectId: row.projectId,
    core.LockedBlockDocumentFields.archivedAt:
        _storedDateTimeOrNull(row.archivedAtUtc),
  });
}

/// Top-level helper that performs the `_lockedOverrideCompanion` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
LockedOverridesCompanion _lockedOverrideCompanion(
  core.LockedBlockOverride override, {
  required core.OwnerId ownerId,
  required core.Revision revision,
}) {
  final doc = core.LockedBlockOverrideDocumentMapping.toDocument(
    override,
    ownerId: ownerId.value,
    revision: revision.value,
  );
  return LockedOverridesCompanion.insert(
    id: override.id,
    ownerId: ownerId.value,
    lockedBlockId: drift.Value(_nullableString(
      doc,
      core.LockedBlockOverrideDocumentFields.lockedBlockId,
    )),
    date: _string(doc, core.LockedBlockOverrideDocumentFields.date),
    type: _string(doc, core.LockedBlockOverrideDocumentFields.type),
    name: drift.Value(
      _nullableString(doc, core.LockedBlockOverrideDocumentFields.name),
    ),
    startTime: drift.Value(_nullableString(
      doc,
      core.LockedBlockOverrideDocumentFields.startTime,
    )),
    endTime: drift.Value(_nullableString(
      doc,
      core.LockedBlockOverrideDocumentFields.endTime,
    )),
    hiddenByDefault:
        _bool(doc, core.LockedBlockOverrideDocumentFields.hiddenByDefault),
    projectId: drift.Value(_nullableString(
      doc,
      core.LockedBlockOverrideDocumentFields.projectId,
    )),
    revision: revision.value,
    createdAtUtc: override.createdAt.toUtc(),
    updatedAtUtc: override.updatedAt.toUtc(),
  );
}

/// Top-level helper that performs the `_lockedOverrideFromRow` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
core.LockedBlockOverride _lockedOverrideFromRow(LockedOverrideRow row) {
  return core.LockedBlockOverrideDocumentMapping.fromDocument({
    ..._commonDocumentFields(
        row.id, row.ownerId, row.revision, row.createdAtUtc, row.updatedAtUtc),
    core.LockedBlockOverrideDocumentFields.lockedBlockId: row.lockedBlockId,
    core.LockedBlockOverrideDocumentFields.date: row.date,
    core.LockedBlockOverrideDocumentFields.type: row.type,
    core.LockedBlockOverrideDocumentFields.name: row.name,
    core.LockedBlockOverrideDocumentFields.startTime: row.startTime,
    core.LockedBlockOverrideDocumentFields.endTime: row.endTime,
    core.LockedBlockOverrideDocumentFields.hiddenByDefault: row.hiddenByDefault,
    core.LockedBlockOverrideDocumentFields.projectId: row.projectId,
  });
}

/// Top-level helper that performs the `_settingsCompanion` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
SettingsTableCompanion _settingsCompanion(
  core.OwnerSettings settings, {
  required core.Revision revision,
  required DateTime createdAt,
  required DateTime updatedAt,
}) {
  final doc = core.OwnerSettingsDocumentMapping.toDocument(
    settings,
    revision: revision.value,
    createdAt: createdAt,
    updatedAt: updatedAt,
  );
  return SettingsTableCompanion.insert(
    ownerId: settings.ownerId,
    timeZoneId: _string(doc, core.OwnerSettingsDocumentFields.timeZoneId),
    dayStartMinutes: settings.dayStart.minutesSinceMidnight,
    dayEndMinutes: settings.dayEnd.minutesSinceMidnight,
    compactMode:
        _bool(doc, core.OwnerSettingsDocumentFields.compactModeEnabled),
    backlogStalenessJson:
        jsonEncode(doc[core.OwnerSettingsDocumentFields.backlogStaleness]),
    revision: revision.value,
    createdAtUtc: createdAt.toUtc(),
    updatedAtUtc: updatedAt.toUtc(),
  );
}

/// Top-level helper that performs the `_settingsFromRow` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
core.OwnerSettings _settingsFromRow(SettingsRow row) {
  return core.OwnerSettingsDocumentMapping.fromDocument({
    ..._commonDocumentFields(row.ownerId, row.ownerId, row.revision,
        row.createdAtUtc, row.updatedAtUtc),
    core.OwnerSettingsDocumentFields.timeZoneId: row.timeZoneId,
    core.OwnerSettingsDocumentFields.dayStart:
        _wallTimeFromMinutes(row.dayStartMinutes).toIsoString(),
    core.OwnerSettingsDocumentFields.dayEnd:
        _wallTimeFromMinutes(row.dayEndMinutes).toIsoString(),
    core.OwnerSettingsDocumentFields.compactModeEnabled: row.compactMode,
    core.OwnerSettingsDocumentFields.backlogStaleness:
        _jsonMap(row.backlogStalenessJson),
  });
}

/// Top-level helper that performs the `_snapshotCompanion` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
SnapshotsCompanion _snapshotCompanion(
  core.SchedulingStateSnapshot snapshot, {
  required core.OwnerId ownerId,
  required core.Revision revision,
}) {
  final retentionExpiresAt = snapshot.capturedAt.add(_snapshotRetention);
  final doc = core.SchedulingSnapshotDocumentMapping.toDocument(
    snapshot,
    ownerId: ownerId.value,
    revision: revision.value,
    retentionExpiresAt: retentionExpiresAt,
  );
  return SnapshotsCompanion.insert(
    id: snapshot.id,
    ownerId: ownerId.value,
    capturedAtUtc: snapshot.capturedAt.toUtc(),
    operationName: drift.Value(_nullableString(
      doc,
      core.SchedulingSnapshotDocumentFields.operationName,
    )),
    sourceDate: drift.Value(_nullableString(
      doc,
      core.SchedulingSnapshotDocumentFields.sourceDate,
    )),
    targetDate: drift.Value(_nullableString(
      doc,
      core.SchedulingSnapshotDocumentFields.targetDate,
    )),
    windowJson: jsonEncode(doc[core.SchedulingSnapshotDocumentFields.window]),
    tasksJson: jsonEncode(doc[core.SchedulingSnapshotDocumentFields.tasks]),
    lockedIntervalsJson:
        jsonEncode(doc[core.SchedulingSnapshotDocumentFields.lockedIntervals]),
    requiredVisibleIntervalsJson: jsonEncode(
      doc[core.SchedulingSnapshotDocumentFields.requiredVisibleIntervals],
    ),
    noticesJson: jsonEncode(doc[core.SchedulingSnapshotDocumentFields.notices]),
    changesJson: jsonEncode(doc[core.SchedulingSnapshotDocumentFields.changes]),
    overlapsJson:
        jsonEncode(doc[core.SchedulingSnapshotDocumentFields.overlaps]),
    retentionExpiresUtc: retentionExpiresAt.toUtc(),
    truncated: _bool(doc, core.SchedulingSnapshotDocumentFields.truncated),
    revision: revision.value,
    createdAtUtc: snapshot.capturedAt.toUtc(),
    updatedAtUtc: snapshot.capturedAt.toUtc(),
  );
}

/// Top-level helper that performs the `_snapshotFromRow` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
core.SchedulingStateSnapshot _snapshotFromRow(SnapshotRow row) {
  return core.SchedulingSnapshotDocumentMapping.fromDocument({
    ..._commonDocumentFields(
        row.id, row.ownerId, row.revision, row.createdAtUtc, row.updatedAtUtc),
    core.SchedulingSnapshotDocumentFields.capturedAt:
        core.PersistenceDateTimeConvention.toStoredString(row.capturedAtUtc),
    core.SchedulingSnapshotDocumentFields.sourceDate: row.sourceDate,
    core.SchedulingSnapshotDocumentFields.targetDate: row.targetDate,
    core.SchedulingSnapshotDocumentFields.window: _jsonMap(row.windowJson),
    core.SchedulingSnapshotDocumentFields.tasks: _jsonList(row.tasksJson),
    core.SchedulingSnapshotDocumentFields.lockedIntervals:
        _jsonList(row.lockedIntervalsJson),
    core.SchedulingSnapshotDocumentFields.requiredVisibleIntervals:
        _jsonList(row.requiredVisibleIntervalsJson),
    core.SchedulingSnapshotDocumentFields.notices: _jsonList(row.noticesJson),
    core.SchedulingSnapshotDocumentFields.changes: _jsonList(row.changesJson),
    core.SchedulingSnapshotDocumentFields.overlaps: _jsonList(row.overlapsJson),
    core.SchedulingSnapshotDocumentFields.operationName: row.operationName,
    core.SchedulingSnapshotDocumentFields.retentionExpiresAt:
        core.PersistenceDateTimeConvention.toStoredString(
      row.retentionExpiresUtc,
    ),
    core.SchedulingSnapshotDocumentFields.truncated: row.truncated,
  });
}

/// Top-level helper that performs the `_commonDocumentFields` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
Map<String, Object?> _commonDocumentFields(
  String id,
  String ownerId,
  int revision,
  DateTime createdAt,
  DateTime updatedAt,
) {
  return <String, Object?>{
    core.DocumentFields.schemaVersion: core.v1SchemaVersion,
    core.DocumentFields.id: id,
    core.DocumentFields.ownerId: ownerId,
    core.DocumentFields.revision: revision,
    core.DocumentFields.createdAt:
        core.PersistenceDateTimeConvention.toStoredString(createdAt),
    core.DocumentFields.updatedAt:
        core.PersistenceDateTimeConvention.toStoredString(updatedAt),
  };
}

/// Top-level helper that performs the `_string` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
String _string(Map<String, Object?> doc, String fieldName) {
  return doc[fieldName] as String;
}

/// Top-level helper that performs the `_nullableString` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
String? _nullableString(Map<String, Object?> doc, String fieldName) {
  return doc[fieldName] as String?;
}

/// Top-level helper that performs the `_nullableInt` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
int? _nullableInt(Map<String, Object?> doc, String fieldName) {
  return doc[fieldName] as int?;
}

/// Top-level helper that performs the `_bool` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
bool _bool(Map<String, Object?> doc, String fieldName) {
  return doc[fieldName] as bool;
}

/// Top-level helper that performs the `_nullableDateTime` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
DateTime? _nullableDateTime(Map<String, Object?> doc, String fieldName) {
  final value = doc[fieldName] as String?;
  return value == null
      ? null
      : core.PersistenceDateTimeConvention.fromStoredString(value);
}

/// Top-level helper that performs the `_storedDateTimeOrNull` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
String? _storedDateTimeOrNull(DateTime? value) {
  return value == null
      ? null
      : core.PersistenceDateTimeConvention.toStoredString(value);
}

/// Top-level helper that performs the `_jsonEncodeNullable` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
String? _jsonEncodeNullable(Object? value) {
  return value == null ? null : jsonEncode(value);
}

/// Top-level helper that performs the `_jsonMap` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
Map<String, Object?> _jsonMap(String value) {
  return Map<String, Object?>.from(
    jsonDecode(value) as Map<dynamic, dynamic>,
  );
}

/// Top-level helper that performs the `_jsonList` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
List<Object?> _jsonList(String value) {
  return List<Object?>.from(jsonDecode(value) as List<dynamic>);
}

/// Top-level helper that performs the `_wallTimeFromMinutes` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
core.WallTime _wallTimeFromMinutes(int minutes) {
  return core.WallTime(hour: minutes ~/ 60, minute: minutes % 60);
}

/// Top-level helper that performs the `_cursorOffset` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
int _cursorOffset(String? cursor) {
  if (cursor == null) return 0;
  final parsed = int.tryParse(cursor);
  if (parsed == null || parsed < 0) return 0;
  return parsed;
}
