import '../../domain/entities/user_entity.dart';

/// User model that extends UserEntity for data layer
///
/// Handles JSON serialization/deserialization for API responses
class UserModel extends UserEntity {
  const UserModel({
    required super.userId,
    required super.username,
    required super.accessToken,
    super.refreshToken,
  });

  /// Create UserModel from JSON response
  ///
  /// Expected JSON format from API:
  /// ```json
  /// {
  ///   "AccessToken": "string"
  /// }
  /// ```
  factory UserModel.fromJson(Map<String, dynamic> json, {String? username}) {
    return UserModel(
      userId: username ?? 'user', // Use username as userId or default
      username: username ?? 'user',
      accessToken: json['AccessToken'] as String,
      refreshToken: null, // API doesn't provide refresh token
    );
  }

  /// Convert UserModel to JSON
  Map<String, dynamic> toJson() {
    return {
      'userId': userId,
      'username': username,
      'accessToken': accessToken,
      'refreshToken': refreshToken,
    };
  }

  /// Create UserModel from UserEntity
  factory UserModel.fromEntity(UserEntity entity) {
    return UserModel(
      userId: entity.userId,
      username: entity.username,
      accessToken: entity.accessToken,
      refreshToken: entity.refreshToken,
    );
  }

  /// Convert to UserEntity
  UserEntity toEntity() {
    return UserEntity(
      userId: userId,
      username: username,
      accessToken: accessToken,
      refreshToken: refreshToken,
    );
  }

  /// Create a copy with modified fields
  @override
  UserModel copyWith({
    String? userId,
    String? username,
    String? accessToken,
    String? refreshToken,
  }) {
    return UserModel(
      userId: userId ?? this.userId,
      username: username ?? this.username,
      accessToken: accessToken ?? this.accessToken,
      refreshToken: refreshToken ?? this.refreshToken,
    );
  }

  @override
  String toString() {
    return 'UserModel(userId: $userId, username: $username, hasRefreshToken: ${refreshToken != null})';
  }
}
