import { defineStore } from 'pinia';
import { useAuthStore } from './auth';

export const useCrudStore = defineStore('crud', {
    actions: {
        async crudRequest({ endpoint, method, parameters }: { endpoint: string; method: string; parameters?: any }) {
            const authStore = useAuthStore();

            let combinedAbsoluteUrl = endpoint;
            if (window.LARAVEL_VAPOR_ENABLED) {
                endpoint = this.encodeSpecificPartOfUrl(endpoint);
                let queryDomain = endpoint.split('?')[0];
                let encodedParams = endpoint.split('?')[1];
                let decodedParams = this.fullyDecodeURI(encodedParams);
                const queryParams = encodeURIComponent(decodedParams);
                queryDomain = this.encodeUrlWithoutQueryParameter(queryDomain);

                encodedParams = queryParams.toString();
                let filteredEncodedParams = encodedParams.replace(/%3D/g, '=');
                filteredEncodedParams = filteredEncodedParams.replace(/%26/g, '&');
                combinedAbsoluteUrl = queryDomain;
                if (filteredEncodedParams !== undefined && filteredEncodedParams !== 'undefined') {
                    combinedAbsoluteUrl = queryDomain + '?' + filteredEncodedParams;
                }
            }

            await authStore.ensureReCaptchaIsSet();

            const response = await fetch(combinedAbsoluteUrl, {
                method: method,
                body: parameters ? JSON.stringify(parameters) : null,
                headers: {
                    'content-type': 'application/json',
                    'Authorization': 'Bearer ' + authStore.access_token,
                    'captcha-token': authStore.getReCaptcha || ''
                }
            });

            if (response.status === 401 && window.location.href !== route('login')) {
                authStore.userAuthentication({ access_token: '', redirect_url: '/' });
            }

            return response;
        },

        isEncoded(uri: string) {
            uri = uri || '';
            return uri !== decodeURIComponent(uri);
        },

        fullyDecodeURI(uri: string) {
            while (this.isEncoded(uri)) {
                uri = decodeURIComponent(uri);
            }
            return uri;
        },

        encodeUrlWithoutQueryParameter(url: string) {
            let regex = /\[\d+\]/;
            let match = url.match(regex);

            if (match) {
                let encodedPattern = encodeURIComponent(match[0]);
                let encodedUrl = url.replace(match[0], encodedPattern);
                return encodedUrl;
            }

            return url;
        },

        encodeSpecificPartOfUrl(url: string) {
            let encodedUrl = url.replace('[', '%5B');
            encodedUrl = encodedUrl.replace(']', '%5D');
            encodedUrl = encodedUrl.replace(',', '%2C');
            return encodedUrl;
        }
    }
});
