import 'user.dart';

class LoginResponse {
  const LoginResponse({
    required this.accessToken,
    this.tokenType = 'bearer',
    required this.userId,
    required this.role,
    this.routeId,
    this.user,
  });

  final String accessToken;
  final String tokenType;
  final String userId;
  final String role;
  final String? routeId;
  final User? user;

  factory LoginResponse.fromJson(Map<String, dynamic> json) {
    final payload = json['data'] is Map<String, dynamic>
        ? json['data'] as Map<String, dynamic>
        : json;

    final userJson = payload['user'] is Map<String, dynamic>
        ? payload['user'] as Map<String, dynamic>
        : null;

    return LoginResponse(
      accessToken:
          _pickString(<dynamic>[
            payload['access_token'],
            payload['token'],
            payload['jwt'],
            json['access_token'],
            json['token'],
            json['jwt'],
          ]) ??
          '',
      tokenType:
          _pickString(<dynamic>[
            payload['token_type'],
            payload['tokenType'],
            json['token_type'],
            json['tokenType'],
          ]) ??
          'bearer',
      userId:
          _pickString(<dynamic>[
            payload['user_id'],
            payload['userId'],
            payload['id'],
            json['user_id'],
            json['userId'],
            json['id'],
          ]) ??
          '',
      role:
          _pickString(<dynamic>[
            payload['role'],
            payload['user_role'],
            payload['userRole'],
            json['role'],
            json['user_role'],
            json['userRole'],
          ]) ??
          'citizen',
      routeId: _pickString(<dynamic>[
        payload['route_id'],
        payload['routeId'],
        json['route_id'],
        json['routeId'],
      ]),
      user: userJson == null ? null : User.fromJson(userJson),
    );
  }

  Map<String, dynamic> toJson() {
    return <String, dynamic>{
      'access_token': accessToken,
      'token_type': tokenType,
      'user_id': userId,
      'role': role,
      'route_id': routeId,
      if (user != null) 'user': user!.toJson(),
    };
  }

  static String? _pickString(Iterable<dynamic> candidates) {
    for (final candidate in candidates) {
      if (candidate is String && candidate.isNotEmpty) {
        return candidate;
      }
      if (candidate != null && candidate.toString().isNotEmpty) {
        return candidate.toString();
      }
    }

    return null;
  }
}
