import 'package:prosapp_web_app/models/pro_state.dart';

class Usuario {
  final String id;
  final String? email;
  final String? phone;
  final String name;
  final String? nickname;
  final String? city;
  final String? picture;
  final String? birthday;
  final String? gender;
  final ProState proState;
  final DateTime? proRejectedAt;
  final String? token;
  final bool isPhoneVerified;

  Usuario({
    required this.id,
    required this.email,
    required this.phone,
    required this.name,
    required this.nickname,
    required this.city,
    required this.picture,
    required this.birthday,
    required this.gender,
    required this.proState,
    required this.token,
    this.proRejectedAt,
    this.isPhoneVerified = false,
  });

  Map<String, Object?> toDocument() {
    return {
      'id': id,
      'email': email,
      'phone': phone,
      'name': name,
      'nickname': name.toLowerCase().trim().replaceAll(' ', '_'),
      'city': city,
      'picture': picture,
      'birthday': birthday,
      'gender': gender,
      'professional_state': enumToInt(proState),
      'token': token,
    };
  }

  static Usuario fromDocument(Map<String, dynamic> doc) {
    return Usuario(
      id: (doc['id'] as String?) ?? '',
      email: doc['email'],
      phone: doc['phone'],
      name: doc['name'] ?? '',
      nickname: doc['nickname'],
      city: doc['city'],
      picture: doc['picture'],
      birthday: doc['birthday'],
      gender: doc['gender'],
      proState: intToEnum((doc['professional_state'] as int?) ?? 0),
      proRejectedAt: _parseRejectedAt(doc),
      token: doc['token'],
      isPhoneVerified: doc['is_phone_verified'] as bool? ?? false,
    );
  }

  static DateTime? _parseRejectedAt(Map<String, dynamic> doc) {
    // /auth/me returns professionals nested; if pro_state==3 use professionals.updated_at
    final state = (doc['professional_state'] as int?) ?? 0;
    if (state != 3) return null;
    final pros = doc['professionals'];
    if (pros is Map) {
      final raw = pros['updated_at'];
      if (raw is String) return DateTime.tryParse(raw);
    }
    return null;
  }

  @override
  String toString() {
    return 'User(id: $id, email: $email, phone: $phone, name: $name, nickname: $nickname, city: $city, picture: $picture, birthday: $birthday, gender: $gender, proState: $proState, token: $token)';
  }
}
