import 'package:json_annotation/json_annotation.dart';

part 'activity.g.dart';

@JsonSerializable()
class Activity {
  final int id;
  final String type;
  final String application;
  final Map<String, dynamic>? metadata;
  @JsonKey(fromJson: _timestampFromJson, toJson: _timestampToJson)
  final DateTime timestamp;
  @JsonKey(name: 'duration_seconds')
  final int durationSeconds;

  Activity({
    required this.id,
    required this.type,
    required this.application,
    this.metadata,
    required this.timestamp,
    required this.durationSeconds,
  });

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

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

  static DateTime _timestampFromJson(dynamic timestamp) {
    if (timestamp is int) {
      return DateTime.fromMillisecondsSinceEpoch(timestamp);
    } else if (timestamp is String) {
      return DateTime.parse(timestamp);
    }
    throw ArgumentError('Invalid timestamp format: $timestamp');
  }

  static int _timestampToJson(DateTime timestamp) {
    return timestamp.millisecondsSinceEpoch;
  }
}
