import 'package:dio/dio.dart';
import 'package:intl/intl.dart';

import '../../../../../api/marianumconnect/errors/marianumconnect_error.dart';
import '../../../../../api/marianumconnect/marianumconnect_api.dart';
import '../../../../../api/marianumconnect/marianumconnect_endpoint.dart';
import '../bloc/marianum_message_state.dart';

/// Loads the "Marianum Message" list from `GET /api/mobile/v1/newsletter`
/// (formerly the mhsl.eu `message/messages.json` endpoint). Bearer token is
/// attached by the shared Marianum-Connect dio.
class MarianumMessageGetMessages {
  final Dio _dio;

  MarianumMessageGetMessages({Dio? dio}) : _dio = dio ?? MarianumConnectApi.dio();

  Future<MarianumMessageList> run() async {
    try {
      final response = await _dio.get<List<dynamic>>(
        MarianumConnectEndpoint.resolve('newsletter'),
      );
      final messages = (response.data ?? const [])
          .cast<Map<String, dynamic>>()
          .map(_mapItem)
          .toList();
      return MarianumMessageList(
        base: MarianumConnectEndpoint.current(),
        messages: messages,
      );
    } on DioException catch (e) {
      throw mapMarianumConnectError(e);
    }
  }

  MarianumMessage _mapItem(Map<String, dynamic> map) => MarianumMessage(
    id: map['id'] as String,
    name: map['title'] as String? ?? '',
    date: _formatDate(map['date'] as String?),
    description: map['description'] as String? ?? '',
    url: map['fileUrl'] as String? ?? '',
  );

  static final DateFormat _monthYear = DateFormat.yMMMM('de');

  /// Server sends ISO `yyyy-MM-dd`; the list shows only the German month + year
  /// (e.g. "April 2024").
  static String _formatDate(String? iso) {
    if (iso == null || iso.isEmpty) return '';
    final parsed = DateTime.tryParse(iso);
    if (parsed == null) return iso;
    return _monthYear.format(parsed);
  }
}
