import 'package:intl/intl.dart';
import 'package:marco/helpers/services/app_logger.dart';

class DateTimeUtils {
  /// Converts a UTC datetime string to local time and formats it.
  static String convertUtcToLocal(String utcTimeString, {String format = 'dd-MM-yyyy'}) {
    try {
      logSafe('Received UTC string: $utcTimeString'); // 🔹 Log input

      final parsed = DateTime.parse(utcTimeString);
      final utcDateTime = DateTime.utc(
        parsed.year,
        parsed.month,
        parsed.day,
        parsed.hour,
        parsed.minute,
        parsed.second,
        parsed.millisecond,
        parsed.microsecond,
      );

      final localDateTime = utcDateTime.toLocal();

      final formatted = _formatDateTime(localDateTime, format: format);

      logSafe('Converted Local DateTime: $localDateTime'); // 🔹 Log raw local datetime
      logSafe('Formatted Local DateTime: $formatted');     // 🔹 Log formatted string

      return formatted;
    } catch (e, stackTrace) {
      logSafe('DateTime conversion failed: $e',
          error: e, stackTrace: stackTrace);
      return 'Invalid Date';
    }
  }

  /// Public utility for formatting any DateTime.
  static String formatDate(DateTime date, String format) {
    try {
      final formatted = DateFormat(format).format(date);
      logSafe('Formatted DateTime ($date) => $formatted'); // 🔹 Log input/output
      return formatted;
    } catch (e, stackTrace) {
      logSafe('formatDate failed: $e', error: e, stackTrace: stackTrace);
      return 'Invalid Date';
    }
  }

  /// Internal formatter with default format.
  static String _formatDateTime(DateTime dateTime, {String format = 'dd-MM-yyyy'}) {
    return DateFormat(format).format(dateTime);
  }
}
