import 'package:json_annotation/json_annotation.dart';

import '../api/marianumconnect/queries/timetable_get_element_week/timetable_element_type.dart';

part 'timetable_favorites_settings.g.dart';

/// A timetable element the user starred for quick access from the picker.
@JsonSerializable(explicitToJson: true)
class FavoriteTimetableElement {
  final TimetableElementType type;
  final int id;
  final String label;

  FavoriteTimetableElement({
    required this.type,
    required this.id,
    required this.label,
  });

  factory FavoriteTimetableElement.fromJson(Map<String, dynamic> json) =>
      _$FavoriteTimetableElementFromJson(json);
  Map<String, dynamic> toJson() => _$FavoriteTimetableElementToJson(this);
}

@JsonSerializable(explicitToJson: true)
class TimetableFavoritesSettings {
  List<FavoriteTimetableElement> favorites;

  TimetableFavoritesSettings({required this.favorites});

  bool isFavorite(TimetableElementType type, int id) =>
      favorites.any((f) => f.type == type && f.id == id);

  /// Adds or removes the element in place. Returns the new favorite state
  /// (`true` = now starred). Callers persist via `SettingsCubit.val(write: true)`.
  bool toggle(TimetableElementType type, int id, String label) {
    final existing = favorites.where((f) => f.type == type && f.id == id);
    if (existing.isNotEmpty) {
      favorites.removeWhere((f) => f.type == type && f.id == id);
      return false;
    }
    favorites.add(FavoriteTimetableElement(type: type, id: id, label: label));
    return true;
  }

  factory TimetableFavoritesSettings.fromJson(Map<String, dynamic> json) =>
      _$TimetableFavoritesSettingsFromJson(json);
  Map<String, dynamic> toJson() => _$TimetableFavoritesSettingsToJson(this);
}
