package com.vpnpanel.security;

import android.content.Context;
import android.content.SharedPreferences;
import androidx.security.crypto.EncryptedSharedPreferences;
import androidx.security.crypto.MasterKey;

import java.io.IOException;
import java.security.GeneralSecurityException;

/**
 * ذخیره‌سازی رمزنگاری شده برای Token و اطلاعات حساس
 */
public class EncryptedStorage {

    private static EncryptedStorage instance;
    private SharedPreferences sharedPreferences;

    private EncryptedStorage(Context context) {
        try {
            MasterKey masterKey = new MasterKey.Builder(context)
                .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
                .build();

            sharedPreferences = EncryptedSharedPreferences.create(
                context,
                "vpn_panel_secure_prefs",
                masterKey,
                EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
            );
        } catch (GeneralSecurityException | IOException e) {
            throw new RuntimeException("Failed to create encrypted storage", e);
        }
    }

    public static synchronized EncryptedStorage getInstance(Context context) {
        if (instance == null) {
            instance = new EncryptedStorage(context);
        }
        return instance;
    }

    public void saveToken(String token) {
        sharedPreferences.edit().putString("auth_token", token).apply();
    }

    public String getToken() {
        return sharedPreferences.getString("auth_token", null);
    }

    public void saveRefreshToken(String refreshToken) {
        sharedPreferences.edit().putString("refresh_token", refreshToken).apply();
    }

    public String getRefreshToken() {
        return sharedPreferences.getString("refresh_token", null);
    }

    public void saveUserId(String userId) {
        sharedPreferences.edit().putString("user_id", userId).apply();
    }

    public String getUserId() {
        return sharedPreferences.getString("user_id", null);
    }

    public void saveUserEmail(String email) {
        sharedPreferences.edit().putString("user_email", email).apply();
    }

    public String getUserEmail() {
        return sharedPreferences.getString("user_email", null);
    }

    public void clearAll() {
        sharedPreferences.edit().clear().apply();
    }

    public boolean isLoggedIn() {
        return getToken() != null;
    }
}
