import 'target_analysis.dart';

class Session {
  final String id;
  final String weapon;
  final String? weaponId;
  final int maxShotsPerTarget;
  final List<TargetAnalysis> analyses;
  final DateTime createdAt;
  final String? notes;
  final int distance; // Shooting distance in meters

  Session({
    required this.id,
    required this.weapon,
    this.weaponId,
    required this.maxShotsPerTarget,
    required this.analyses,
    required this.createdAt,
    this.notes,
    this.distance = 25, // Default distance
  });

  int get targetCount => analyses.length;
  
  int get totalShots => analyses.fold(0, (sum, a) => sum + a.shotCount);
  
  int get totalScore => analyses.fold(0, (sum, a) => sum + a.totalScore);

  double get averageScore => analyses.isEmpty ? 0.0 : totalScore / analyses.length;

  Session copyWith({
    String? id,
    String? weapon,
    String? weaponId,
    int? maxShotsPerTarget,
    List<TargetAnalysis>? analyses,
    DateTime? createdAt,
    String? notes,
    int? distance,
  }) {
    return Session(
      id: id ?? this.id,
      weapon: weapon ?? this.weapon,
      weaponId: weaponId ?? this.weaponId,
      maxShotsPerTarget: maxShotsPerTarget ?? this.maxShotsPerTarget,
      analyses: analyses ?? this.analyses,
      createdAt: createdAt ?? this.createdAt,
      notes: notes ?? this.notes,
      distance: distance ?? this.distance,
    );
  }

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'weapon': weapon,
      'weapon_id': weaponId,
      'max_shots_per_target': maxShotsPerTarget,
      'created_at': createdAt.toIso8601String(),
      'notes': notes,
      'distance': distance,
    };
  }

  factory Session.fromMap(Map<String, dynamic> map, List<TargetAnalysis> analyses) {
    return Session(
      id: map['id'] as String,
      weapon: map['weapon'] as String? ?? 'Inconnue',
      weaponId: map['weapon_id'] as String?,
      maxShotsPerTarget: map['max_shots_per_target'] as int? ?? 5,
      analyses: analyses,
      createdAt: DateTime.parse(map['created_at'] as String),
      notes: map['notes'] as String?,
      distance: map['distance'] as int? ?? 25,
    );
  }

  @override
  String toString() {
    return 'Session(id: $id, weapon: $weapon, distance: ${distance}m, targets: ${analyses.length}, createdAt: $createdAt)';
  }
}
