import 'group_member.dart';

/// Model representing a travel group.
///
/// A group is a collection of travelers who are part of a specific trip.
/// It contains information about group members, creation details, and
/// provides methods for serialization with Firestore.
class Group {
  /// Unique identifier for the group
  final String id;

  /// Display name of the group
  final String name;

  /// ID of the trip this group belongs to
  final String tripId;

  /// ID of the user who created this group
  final String createdBy;

  /// Timestamp when the group was created
  final DateTime createdAt;

  /// Timestamp when the group was last updated
  final DateTime updatedAt;

  /// List of members in this group
  final List<GroupMember> members;

  /// List of member IDs for efficient querying and security rules
  final List<String> memberIds;

  /// Creates a new [Group] instance.
  ///
  /// [id], [name], [tripId], and [createdBy] are required.
  /// [createdAt] and [updatedAt] default to current time if not provided.
  /// [members] defaults to empty list if not provided.
  Group({
    required this.id,
    required this.name,
    required this.tripId,
    required this.createdBy,
    DateTime? createdAt,
    DateTime? updatedAt,
    List<GroupMember>? members,
    List<String>? memberIds,
  }) : createdAt = createdAt ?? DateTime.now(),
       updatedAt = updatedAt ?? DateTime.now(),
       members = members ?? [],
       memberIds = memberIds ?? [];

  /// Creates a [Group] instance from a Firestore document map.
  ///
  /// [map] - The document data from Firestore
  /// [id] - The document ID from Firestore
  ///
  /// Returns a new [Group] instance with data from the map.
  factory Group.fromMap(Map<String, dynamic> map, String id) {
    return Group(
      id: id,
      name: map['name'] ?? '',
      tripId: map['tripId'] ?? '',
      createdBy: map['createdBy'] ?? '',
      createdAt: DateTime.fromMillisecondsSinceEpoch(map['createdAt'] ?? 0),
      updatedAt: DateTime.fromMillisecondsSinceEpoch(map['updatedAt'] ?? 0),
      members: [],
      memberIds: List<String>.from(map['memberIds'] ?? []),
    );
  }

  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'tripId': tripId,
      'createdBy': createdBy,
      'createdAt': createdAt.millisecondsSinceEpoch,
      'updatedAt': updatedAt.millisecondsSinceEpoch,
      'memberIds': memberIds,
    };
  }

  Group copyWith({
    String? id,
    String? name,
    String? tripId,
    String? createdBy,
    DateTime? createdAt,
    DateTime? updatedAt,
    List<GroupMember>? members,
    List<String>? memberIds,
  }) {
    return Group(
      id: id ?? this.id,
      name: name ?? this.name,
      tripId: tripId ?? this.tripId,
      createdBy: createdBy ?? this.createdBy,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
      members: members ?? this.members,
      memberIds: memberIds ?? this.memberIds,
    );
  }
}
