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

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

/// Document mapping for [TaskActivity].
abstract final class TaskActivityDocumentMapping {
  /// 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(
    TaskActivity activity, {
    required String ownerId,
    int revision = 1,
    DateTime? createdAt,
    DateTime? updatedAt,
  }) {
    final created = createdAt ?? activity.occurredAt;
    final updated = updatedAt ?? created;
    return {
      ..._commonFields(
        id: activity.id,
        ownerId: ownerId,
        revision: revision,
        createdAt: created,
        updatedAt: updated,
      ),
      TaskActivityDocumentFields.operationId: activity.operationId,
      TaskActivityDocumentFields.code:
          PersistenceEnumMapping.encodeTaskActivityCode(activity.code),
      TaskActivityDocumentFields.taskId: activity.taskId,
      TaskActivityDocumentFields.projectId: activity.projectId,
      TaskActivityDocumentFields.occurredAt:
          PersistenceDateTimeConvention.toStoredString(activity.occurredAt),
      TaskActivityDocumentFields.metadata: _plainDocument(activity.metadata),
    };
  }

  /// 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 TaskActivity fromDocument(Map<String, Object?> document) {
    return _mapInvalidValues(() {
      _readCommon(document);
      return TaskActivity(
        id: _requiredString(document, TaskActivityDocumentFields.id),
        operationId: _requiredString(
          document,
          TaskActivityDocumentFields.operationId,
        ),
        code: PersistenceEnumMapping.decodeTaskActivityCode(
          _requiredString(document, TaskActivityDocumentFields.code),
        ),
        taskId: _requiredString(document, TaskActivityDocumentFields.taskId),
        projectId:
            _requiredString(document, TaskActivityDocumentFields.projectId),
        occurredAt: _requiredDateTime(
          document,
          TaskActivityDocumentFields.occurredAt,
        ),
        metadata: _requiredMap(document, TaskActivityDocumentFields.metadata),
      );
    });
  }
}
