import 'package:qrscanner/models/login_response.dart';

class AuthSession {
  const AuthSession({
    required this.username,
    required this.accessToken,
    required this.tokenType,
    required this.expiresIn,
    required this.roles,
  });

  factory AuthSession.fromLoginResponse(LoginResponse response) {
    return AuthSession(
      username: response.username ?? '',
      accessToken: response.accessToken ?? '',
      tokenType: response.tokenType ?? 'Bearer',
      expiresIn: response.expiresIn ?? 0,
      roles: response.roles,
    );
  }

  factory AuthSession.fromJson(Map<String, dynamic> json) {
    return AuthSession(
      username: json['username'] as String? ?? '',
      accessToken: json['accessToken'] as String? ?? '',
      tokenType: json['tokenType'] as String? ?? 'Bearer',
      expiresIn: (json['expiresIn'] as num?)?.toInt() ?? 0,
      roles: (json['roles'] as List<dynamic>?)
              ?.map((role) => role.toString())
              .toList() ??
          const [],
    );
  }

  final String username;
  final String accessToken;
  final String tokenType;
  final int expiresIn;
  final List<String> roles;

  String get authorizationHeader => '$tokenType $accessToken';

  bool get isScanner => roles.contains('ROLE_SCANNER');

  Map<String, dynamic> toJson() => {
        'username': username,
        'accessToken': accessToken,
        'tokenType': tokenType,
        'expiresIn': expiresIn,
        'roles': roles,
      };
}