import { useUiStore } from '@/stores/ui';
import { useCrudStore } from '@/stores/crud';
import { useNotificationStore } from '@/stores/notification';

interface RequestOptions {
    validate?: () => boolean | Promise<boolean>;
    successHandler?: (response: any, section?: string, parameters?: any) => void;
    errorHandler?: (response: any, statusCode: number, section?: string) => void;
}

export function useRequest() {
    const uiStore = useUiStore();
    const crudStore = useCrudStore();
    const notificationStore = useNotificationStore();

    async function submit(
        url: string,
        method: string,
        section?: string,
        successNotification = true,
        errorNotification = true,
        parameters?: any,
        options: RequestOptions = {}
    ) {
        // 1. Validation
        if (options.validate) {
            const isValid = await options.validate();
            if (!isValid) return;
        }

        // 2. Start Loading
        if (section) {
            uiStore.toggleLoading(section, true);
        }

        try {
            // 3. API Request
            const response = await crudStore.crudRequest({
                endpoint: url,
                method: method,
                parameters: method.toLowerCase() === 'get' ? null : parameters
            });

            const statusCode = response.status;
            const success = response.ok;

            if (statusCode === 503) {
                window.location.href = '/maintenance';
                return;
            }

            const responseData = await response.json();

            if (!success) {
                // Error Handling
                if (errorNotification) {
                    notificationStore.createNotification({
                        title: responseData.title || 'Error',
                        message: responseData.message || 'Something went wrong',
                        type: 'error'
                    });
                }
                if (options.errorHandler) {
                    options.errorHandler(responseData, statusCode, section);
                }
                return;
            }

            // Success Handling
            if (successNotification) {
                notificationStore.createNotification({
                    title: responseData.title || 'Success',
                    message: responseData.message || 'Operation successful',
                    type: 'success'
                });
            }
            if (options.successHandler) {
                options.successHandler(responseData, section, parameters);
            }

        } catch (error) {
            console.error('Request failed:', error);
            notificationStore.createNotification({
                title: 'Unexpected Error',
                message: 'An unexpected error has occurred. Try again!',
                type: 'error'
            });
        } finally {
            if (typeof (window as any).executeRecaptcha === 'function') {
                (window as any).executeRecaptcha();
            }
            // 4. Stop Loading
            if (section) {
                uiStore.toggleLoading(section, false);
            }
        }
    }

    return {
        submit
    };
}
