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

import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:niogu_app/core/constants/app_key.dart';

class SystemSecure {
  static final _storage = const FlutterSecureStorage();

  static Future<void> generateDatabaseKey(String tenantCode) async {
    final random = Random.secure();

    final values = List<int>.generate(32, (i) => random.nextInt(256));

    await _storage.write(
      key: "${AppKey.DATABASE_ENCRYPTION}_$tenantCode",
      value: base64Url.encode(values),
    );
  }

  static Future<String?> getDatabaseKey(String tenantCode) async {
    return await _storage.read(key: "${AppKey.DATABASE_ENCRYPTION}_$tenantCode");
  }

  static Future<void> saveAccessToken(String accessToken) async {
    await _storage.write(key: AppKey.AUTH_TOKEN, value: accessToken);
  }

  static Future<String?> getAccessToken() async {
    return await _storage.read(key: AppKey.AUTH_TOKEN);
  }

  static Future<void> deleteAccessToken() async {
    await _storage.delete(key: AppKey.AUTH_TOKEN);
  }
}
