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

part of '../../encrypted_backup.dart';

/// Top-level helper that performs the `_nextAvailableBackupFile` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
Future<File> _nextAvailableBackupFile(Directory directory, String name) async {
  final preferred = File(_joinPath(directory.path, name));
  if (!await preferred.exists()) {
    return preferred;
  }
  final dot = name.lastIndexOf('.');
  final stem = dot == -1 ? name : name.substring(0, dot);
  final extension = dot == -1 ? '' : name.substring(dot);
  var counter = 2;
  while (true) {
    final candidate =
        File(_joinPath(directory.path, '$stem-$counter$extension'));
    if (!await candidate.exists()) {
      return candidate;
    }
    counter += 1;
  }
}

/// Top-level helper that performs the `_backupTimestamp` 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 _backupTimestamp(DateTime value) {
  final local = value.toLocal();
  return '${_four(local.year)}${_two(local.month)}${_two(local.day)}_'
      '${_two(local.hour)}${_two(local.minute)}';
}

/// Top-level helper that performs the `_four` 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 _four(int value) => value.toString().padLeft(4, '0');

/// Top-level helper that performs the `_two` 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 _two(int value) => value.toString().padLeft(2, '0');
