import 'dart:convert';
import 'dart:math';

import 'package:crypto/crypto.dart';

import '../../application/application.dart';

final class SecureOpaqueTokenService implements OpaqueTokenService {
  SecureOpaqueTokenService({this.byteLength = 32, Random? random})
    : _random = random ?? Random.secure();

  final int byteLength;
  final Random _random;

  @override
  String generateToken() {
    final bytes = List<int>.generate(byteLength, (_) => _random.nextInt(256));
    return base64UrlEncode(bytes).replaceAll('=', '');
  }

  @override
  String hashToken(String token) {
    return sha256.convert(utf8.encode(token)).toString();
  }
}
