// Store and manage token usage data
import { inject, onMounted, ref } from 'vue';
import { AppConfigType } from '../types';
import Axios from '~src/shared/axios';

// Create reactive values to track token usage
const usedTokens = ref(0);
const totalTokens = ref(0);
const totalTokensAdditional = ref(0);
const isTokenLimitReached = ref(false);
const refreshTokens = ref(0); // This will be used to trigger re-renders

export function useTokensStore() {
    // Init tokens data from config
    const config: AppConfigType = inject('pluginConfig');

    // Update token reached flag
    const updateTokenLimitReached = () => {
		// Temporary flag
		let limitReached = false;

        // Set the limit reached flag if limit is reached
        if (usedTokens.value >= totalTokens.value) {
            limitReached = true;
        }

		// If user has additional tokens set the flag to false
		if (totalTokensAdditional.value && totalTokensAdditional.value > 0) {
			limitReached = false;
		}

		isTokenLimitReached.value = limitReached;
    };

    // Update token values from config on start
    usedTokens.value = config.settings.used_tokens;
    totalTokens.value = config.settings.available_tokens;
    totalTokensAdditional.value = config.settings.available_tokens_additional;

    updateTokenLimitReached();

    // Force refresh the token data and trigger component updates
    const updateTokens = async () => {
        // Update the token values from the API
        const response = await Axios.get(`${config.rest.endpoints.boostsite}/get_user`);

        // Check if the response is successful
        if (response.status !== 200 || !response.data.success || !response.data?.data) {
            throw new Error(`REST API error: ${response.status} - ${response.statusText}`);
        }

        // Extract data
        const data = response.data.data;

        // Update the tokens
        usedTokens.value = data.used_tokens_this_week;
        totalTokens.value = data.account_type === 'FREE' ? 1 : 35;
        totalTokensAdditional.value = data.additional_articles ?? null;

        updateTokenLimitReached();

        // Increment the trigger to notify observers
        refreshTokens.value++;
    };

    return {
        usedTokens,
        totalTokens,
        totalTokensAdditional,
        isTokenLimitReached,
        refreshTokens,
        updateTokens,
    };
}
