import VnInput from 'src/components/common/VnInput.vue';
import { useVnConfirm } from 'src/composables/useVnConfirm';
import axios from 'axios';
import { ref } from 'vue';
import { i18n } from 'src/boot/i18n';
import useNotify from 'src/composables/useNotify.js';

export async function useCau(res, message) {
    const { notify } = useNotify();
    const { openConfirmationModal } = useVnConfirm();
    const { config, headers, request, status, statusText, data } = res || {};
    const { params, url, method, signal, headers: confHeaders } = config || {};
    const { message: resMessage, code, name } = data?.error || {};

    const additionalData = {
        path: location.hash,
        message: resMessage,
        code,
        request: request?.responseURL,
        status,
        name,
        statusText: statusText,
        config: {
            url,
            method,
            params,
            headers: confHeaders,
            aborted: signal?.aborted,
            version: headers?.['salix-version'],
        },
    };
    const opts = {
        actions: [
            {
                icon: 'support_agent',
                color: 'primary',
                dense: true,
                flat: false,
                round: true,
                handler: async () => {
                    const locale = i18n.global.t;
                    const reason = ref(
                        code == 'ACCESS_DENIED' ? locale('cau.askPrivileges') : ''
                    );
                    openConfirmationModal(
                        locale('cau.title'),
                        locale('cau.subtitle'),
                        async () => {
                            await axios.post('OsTickets/send-to-support', {
                                reason: reason.value,
                                additionalData,
                            });
                        },
                        null,
                        {
                            component: VnInput,
                            props: {
                                modelValue: reason,
                                'onUpdate:modelValue': (val) => (reason.value = val),
                                label: locale('cau.inputLabel'),
                                class: 'full-width',
                                required: true,
                                autofocus: true,
                            },
                        }
                    );
                },
            },
        ],
    };

    notify(message ?? 'globals.error', 'negative', 'error', opts);
}
