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

part of '../../document_mapping.dart';

/// Document mapping for [BacklogStalenessSettings].
abstract final class BacklogStalenessDocumentMapping {
  /// Converts scheduler data for `toDocument` without changing the source object.
  /// Conversion helpers keep persistence and export shapes explicit so domain models do not depend on storage-specific details.
  static Map<String, Object?> toDocument(BacklogStalenessSettings settings) {
    return {
      BacklogStalenessDocumentFields.greenMaxAgeDays:
          settings.greenMaxAge.inDays,
      BacklogStalenessDocumentFields.blueMaxAgeDays: settings.blueMaxAge.inDays,
    };
  }

  /// Converts scheduler data for `fromDocument` without changing the source object.
  /// Conversion helpers keep persistence and export shapes explicit so domain models do not depend on storage-specific details.
  static BacklogStalenessSettings fromDocument(Map<String, Object?> document) {
    return _mapInvalidValues(() {
      final greenDays = _requiredInt(
        document,
        BacklogStalenessDocumentFields.greenMaxAgeDays,
      );
      final blueDays = _requiredInt(
        document,
        BacklogStalenessDocumentFields.blueMaxAgeDays,
      );
      if (greenDays < 0 || blueDays < 0 || blueDays < greenDays) {
        throw const DocumentMappingException(
          code: DocumentMappingFailureCode.invalidValue,
          fieldName: OwnerSettingsDocumentFields.backlogStaleness,
          detailCode: 'invalidBacklogStalenessThresholds',
        );
      }
      return BacklogStalenessSettings(
        greenMaxAge: Duration(days: greenDays),
        blueMaxAge: Duration(days: blueDays),
      );
    });
  }
}
