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

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

/// Document mapping for [LockedBlockRecurrence].
abstract final class LockedBlockRecurrenceDocumentMapping {
  /// 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(LockedBlockRecurrence recurrence) {
    return {
      LockedBlockRecurrenceDocumentFields.type: 'weekly',
      LockedBlockRecurrenceDocumentFields.weekdays: recurrence.weekdays
          .map(PersistenceEnumMapping.encodeLockedWeekday)
          .toList(growable: false),
    };
  }

  /// 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 LockedBlockRecurrence fromDocument(Map<String, Object?> document) {
    return _mapInvalidValues(() {
      final type = _requiredString(
        document,
        LockedBlockRecurrenceDocumentFields.type,
      );
      if (type != 'weekly') {
        throw DocumentMappingException(
          code: DocumentMappingFailureCode.unknownCode,
          fieldName: LockedBlockRecurrenceDocumentFields.type,
          detailCode: type,
        );
      }
      final weekdays = _requiredList(
        document,
        LockedBlockRecurrenceDocumentFields.weekdays,
      ).map((value) {
        if (value is! String) {
          throw const DocumentMappingException(
            code: DocumentMappingFailureCode.wrongType,
            fieldName: LockedBlockRecurrenceDocumentFields.weekdays,
          );
        }
        return PersistenceEnumMapping.decodeLockedWeekday(value);
      }).toSet();
      return LockedBlockRecurrence.weekly(weekdays: weekdays);
    });
  }
}
