package com.miraclegarden.smsmessage.network;

import android.content.Context;
import android.content.SharedPreferences;

import com.miraclegarden.smsmessage.model.LoginResponse;
import com.miraclegarden.smsmessage.model.UserInfo;

/**
 * JWT Token管理器
 */
public class TokenManager {
    private static final String PREFS_NAME = "auth_prefs";
    private static final String KEY_TOKEN = "jwt_token";
    private static final String KEY_USER_ID = "user_id";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_ROLE = "role";
    private static final String KEY_IS_FIRST_LOGIN = "is_first_login";

    private final SharedPreferences prefs;
    private static TokenManager instance;

    private TokenManager(Context context) {
        prefs = context.getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }

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

    public void saveLoginData(LoginResponse response) {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(KEY_TOKEN, response.getToken());

        UserInfo user = response.getUser();
        if (user != null) {
            editor.putString(KEY_USER_ID, user.getId());
            editor.putString(KEY_USERNAME, user.getUsername());
            editor.putString(KEY_ROLE, user.getRole());
            editor.putBoolean(KEY_IS_FIRST_LOGIN, user.isFirstLogin());
        }
        editor.apply();
    }

    public String getToken() {
        return prefs.getString(KEY_TOKEN, null);
    }

    public String getAuthHeader() {
        String token = getToken();
        return token != null ? "Bearer " + token : null;
    }

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

    public String getUserId() {
        return prefs.getString(KEY_USER_ID, null);
    }

    public String getUsername() {
        return prefs.getString(KEY_USERNAME, null);
    }

    public String getRole() {
        return prefs.getString(KEY_ROLE, null);
    }

    public boolean isFirstLogin() {
        return prefs.getBoolean(KEY_IS_FIRST_LOGIN, false);
    }

    public void setFirstLoginComplete() {
        prefs.edit().putBoolean(KEY_IS_FIRST_LOGIN, false).apply();
    }

    public void clear() {
        prefs.edit().clear().apply();
    }
}
