import 'package:json_annotation/json_annotation.dart';

part 'focus_session.g.dart';

@JsonSerializable()
class FocusSession {
  final int id;
  @JsonKey(name: 'start_time', fromJson: _dateTimeFromJson, toJson: _dateTimeToJson)
  final DateTime startTime;
  @JsonKey(name: 'end_time', fromJson: _nullableDateTimeFromJson, toJson: _nullableDateTimeToJson)
  final DateTime? endTime;
  @JsonKey(name: 'duration_seconds')
  final int? durationSeconds;
  @JsonKey(name: 'xp_earned')
  final int xpEarned;
  final String status;
  @JsonKey(name: 'created_at', fromJson: _dateTimeFromJson, toJson: _dateTimeToJson)
  final DateTime createdAt;
  @JsonKey(name: 'updated_at', fromJson: _dateTimeFromJson, toJson: _dateTimeToJson)
  final DateTime updatedAt;

  FocusSession({
    required this.id,
    required this.startTime,
    this.endTime,
    this.durationSeconds,
    required this.xpEarned,
    required this.status,
    required this.createdAt,
    required this.updatedAt,
  });

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

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

  static DateTime _dateTimeFromJson(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 _dateTimeToJson(DateTime timestamp) {
    return timestamp.millisecondsSinceEpoch;
  }

  static DateTime? _nullableDateTimeFromJson(dynamic timestamp) {
    if (timestamp == null) return null;
    return _dateTimeFromJson(timestamp);
  }

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