import 'package:json_annotation/json_annotation.dart';

part 'custom_timetable_event.g.dart';

@JsonSerializable()
class CustomTimetableEvent {
  String id;
  String title;
  String description;
  @JsonKey(toJson: _dateToJson, fromJson: _dateFromJson)
  DateTime startDate;
  @JsonKey(toJson: _dateToJson, fromJson: _dateFromJson)
  DateTime endDate;
  String? color;
  String rrule;

  /// When true, occurrences of a recurring event that fall inside a school
  /// holiday are hidden in the calendar. Purely client-side: the backend only
  /// stores the flag, the exclusion is applied at render time against the
  /// holiday list. Ignored for non-recurring events (empty [rrule]).
  @JsonKey(defaultValue: false)
  bool skipHolidays;

  @JsonKey(toJson: _dateToJson, fromJson: _dateFromJson)
  DateTime createdAt;
  @JsonKey(toJson: _dateToJson, fromJson: _dateFromJson)
  DateTime updatedAt;

  CustomTimetableEvent({
    required this.id,
    required this.title,
    required this.description,
    required this.startDate,
    required this.endDate,
    required this.color,
    required this.rrule,
    this.skipHolidays = false,
    required this.createdAt,
    required this.updatedAt,
  });

  factory CustomTimetableEvent.fromJson(Map<String, dynamic> json) =>
      _$CustomTimetableEventFromJson(json);
  Map<String, dynamic> toJson() => _$CustomTimetableEventToJson(this);

  // Marianum-Connect serializes LocalDateTime as ISO-8601 (`yyyy-MM-ddTHH:mm:ss`)
  // and its GSON parser rejects anything else. DateTime.parse still reads the
  // old MHSL `yyyy-MM-dd HH:mm:ss` shape too, so events fetched during the
  // one-time migration deserialize unchanged.
  static DateTime _dateFromJson(String raw) => DateTime.parse(raw);
  static String _dateToJson(DateTime d) =>
      '${d.year.toString().padLeft(4, '0')}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}'
      'T${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}:${d.second.toString().padLeft(2, '0')}';
}
