import 'package:json_annotation/json_annotation.dart';

part 'achievement.g.dart';

@JsonSerializable()
class Achievement {
  final int id;
  final String name;
  final String description;
  @JsonKey(name: 'xp_reward')
  final int xpReward;
  @JsonKey(name: 'achieved_at', fromJson: _achievedAtFromJson, toJson: _achievedAtToJson)
  final DateTime? achievedAt;
  @JsonKey(name: 'level_at_achievement')
  final int? levelAtAchievement;

  Achievement({
    required this.id,
    required this.name,
    required this.description,
    required this.xpReward,
    this.achievedAt,
    this.levelAtAchievement,
  });

  factory Achievement.fromJson(Map<String, dynamic> json) =>
      _$AchievementFromJson(json);

  Map<String, dynamic> toJson() => _$AchievementToJson(this);

  bool get isAchieved => achievedAt != null;

  static DateTime? _achievedAtFromJson(dynamic achievedAt) {
    if (achievedAt == null) return null;
    if (achievedAt is int) {
      return DateTime.fromMillisecondsSinceEpoch(achievedAt);
    } else if (achievedAt is String) {
      return DateTime.parse(achievedAt);
    }
    throw ArgumentError('Invalid achievedAt format: $achievedAt');
  }

  static int? _achievedAtToJson(DateTime? achievedAt) {
    return achievedAt?.millisecondsSinceEpoch;
  }
}
