import 'dart:convert';

import '../../profile/data/models/user_profile_model.dart';

DateTime? resolveDashboardSessionIssuedAt({
  String? token,
  UserProfile? profile,
}) {
  final tokenIssuedAt = _getJwtIssuedAt(token);
  if (tokenIssuedAt != null) {
    return tokenIssuedAt;
  }
  return _parseSessionAuthenticatedAt(profile?.sessionAuthenticatedAt);
}

DateTime? _getJwtIssuedAt(String? token) {
  if (token == null || token.isEmpty) {
    return null;
  }
  try {
    final parts = token.split('.');
    if (parts.length != 3) {
      return null;
    }
    final payload = utf8.decode(
      base64Url.decode(base64Url.normalize(parts[1])),
    );
    final data = json.decode(payload) as Map<String, dynamic>;
    final iatValue = data['iat'] ?? data['auth_time'];
    if (iatValue is num) {
      return DateTime.fromMillisecondsSinceEpoch(
        iatValue.toInt() * 1000,
      ).toLocal();
    }
  } catch (_) {
    return null;
  }
  return null;
}

DateTime? _parseSessionAuthenticatedAt(String? value) {
  if (value == null || value.trim().isEmpty) {
    return null;
  }
  try {
    return DateTime.parse(value).toLocal();
  } catch (_) {
    return null;
  }
}
