package com.example.petstoremobile.api.auth;

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

import javax.inject.Inject;
import javax.inject.Singleton;

import dagger.hilt.android.qualifiers.ApplicationContext;

@Singleton
public class TokenManager {
    private static final String TOKEN_KEY = "token";
    private static final String USERNAME_KEY = "username";
    private static final String ROLE_KEY = "role";
    private static final String PREFS_NAME = "auth_prefs";
    private static final String USER_ID_KEY = "user_id";
    private static final String PRIMARY_STORE_ID_KEY = "primary_store_id";

    private SharedPreferences prefs;

    @Inject
    public TokenManager(@ApplicationContext Context context) {
        prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }

    //save login data after login
    public void saveLoginData(String token, String username, String role) {
        prefs.edit()
                .putString(TOKEN_KEY, token)
                .putString(USERNAME_KEY, username)
                .putString(ROLE_KEY, role)
                .apply();
    }

    //Getters
    public String getToken() {
        return prefs.getString(TOKEN_KEY, null);
    }

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

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

    public Long getUserId() {
        long id = prefs.getLong(USER_ID_KEY, -1L);
        return id == -1L ? null : id;
    }

    public void saveUserId(Long userId) {
        prefs.edit().putLong(USER_ID_KEY, userId).apply();
    }

    public void savePrimaryStoreId(Long storeId) {
        if (storeId != null) {
            prefs.edit().putLong(PRIMARY_STORE_ID_KEY, storeId).apply();
        } else {
            prefs.edit().remove(PRIMARY_STORE_ID_KEY).apply();
        }
    }

    public Long getPrimaryStoreId() {
        long id = prefs.getLong(PRIMARY_STORE_ID_KEY, -1L);
        return id == -1L ? null : id;
    }

    //Check if logged in
    public boolean isLoggedIn() {
        return getToken() != null;
    }

    //Clear login data
    public void clearLoginData() {
        prefs.edit().clear().apply();
    }
}