import 'package:prosapp_web_app/models/profesional.dart';
import 'package:prosapp_web_app/models/usuario.dart';

class UsuarioProfesional {
  final Usuario user;
  final Profesional professionalInfo;
  final double averageScore;

  UsuarioProfesional({
    required this.user,
    required this.professionalInfo,
    required this.averageScore,
  });

  // Método para serializar a JSON
  Map<String, dynamic> toJson() {
    return {
      'user': user.toDocument(),
      'professionalInfo': professionalInfo.toDocument(),
      'averageScore': averageScore,
    };
  }

  factory UsuarioProfesional.fromJson(Map<String, dynamic> json) {
    return UsuarioProfesional(
      user: Usuario.fromDocument(json['user']),
      professionalInfo: Profesional.fromDocument(json['professionalInfo']),
      averageScore: (json['averageScore'] as num?)?.toDouble() ?? 0.0,
    );
  }

  static UsuarioProfesional fromDocument(Map<String, dynamic> doc) {
    // Backend from /professionals returns professional at top level with 'users' nested
    // Legacy format uses 'user' and 'professional_info' keys
    final userDoc = (doc['users'] ?? doc['user']) as Map<String, dynamic>?;
    final proDoc = doc.containsKey('professional_info')
        ? doc['professional_info'] as Map<String, dynamic>
        : doc;
    return UsuarioProfesional(
      user: Usuario.fromDocument(userDoc ?? {}),
      professionalInfo: Profesional.fromDocument(proDoc),
      averageScore: (doc['average_score'] as num?)?.toDouble() ?? 0.0,
    );
  }

  @override
  String toString() {
    return '''UsuarioProfesional{
      user: $user, 
      professionalInfo: $professionalInfo,
      averageScore: $averageScore
    }''';
  }
}
