import '../../../api_response.dart';
import '../chat/get_chat_response.dart';

/// Response of Talk's shared-items endpoints. The message objects carry the
/// same structure as regular chat messages, so we reuse [GetChatResponseObject]
/// (the shared file lives in `messageParameters['file']`).
///
/// The server returns `data` either as a list or as a message-id-keyed map
/// depending on version; [fromOcs] normalises both to a list.
class GetSharedItemsResponse extends ApiResponse {
  final List<GetChatResponseObject> items;

  GetSharedItemsResponse(this.items);

  factory GetSharedItemsResponse.fromOcs(Map<String, dynamic> ocs) {
    final data = ocs['data'];
    final raw = switch (data) {
      List<dynamic> list => list,
      Map<dynamic, dynamic> map => map.values,
      _ => const <dynamic>[],
    };
    final items = raw
        .whereType<Map<String, dynamic>>()
        .map(GetChatResponseObject.fromJson)
        .toList();
    return GetSharedItemsResponse(items);
  }

  /// Offset for the next page, taken from the `X-Chat-Last-Given` header.
  /// Null when the header is absent (older server) — treat that as "stop".
  int? get lastGivenMessageId {
    final value = headers?['x-chat-last-given'];
    return value == null ? null : int.tryParse(value);
  }
}
