import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:slrpg_app/src/features/gamification/domain/entities/avatar_config.dart';

part 'party_member.freezed.dart';
part 'party_member.g.dart';

@freezed
abstract class PartyMember with _$PartyMember {
  const factory PartyMember({
    required String id,
    @JsonKey(name: 'user_id') required String userId,
    @JsonKey(name: 'is_ready') required bool isReady,
    @JsonKey(includeFromJson: false) String? username,
    @JsonKey(includeFromJson: false) AvatarConfig? avatar,
  }) = _PartyMember;

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

  factory PartyMember.fromRecord(Map<String, dynamic> json) {
    var member = PartyMember.fromJson(json);

    if (json['expand'] != null && json['expand']['user_id'] != null) {
      final userMap = json['expand']['user_id'] as Map<String, dynamic>;

      AvatarConfig? avatarConfig;
      if (userMap['avatar_config'] != null) {
        try {
          avatarConfig = AvatarConfig.fromJson(userMap['avatar_config']);
        } catch (_) {}
      }

      return member.copyWith(
        username: userMap['name'] ?? userMap['username'] ?? 'Unknown',
        avatar: avatarConfig,
      );
    }
    return member;
  }
}
