import { useBaseConnector } from '@/UI-kit/composables';
import { IApiRequest, IApiResponse, IRawImage } from '@/modules/documents';
import { useUiKitConfigStore } from '@/configs/store';
import { storeToRefs } from 'pinia';

export default function (authToken = '') {
    const configStore = useUiKitConfigStore();
    const { userAuthToken } = storeToRefs(configStore);

    const baseConnector = useBaseConnector(userAuthToken.value || authToken);

    const getDocuments = async (): Promise<IApiResponse> => {
        return baseConnector.get<IApiResponse>('/api/document');
    };

    const saveDocument = async ({
        formData,
    }: {
        formData?: IApiRequest;
    }): Promise<IApiResponse> => {
        return baseConnector.post<IApiResponse>('/api/document', formData);
    };

    const updateDocument = async ({
        formData,
        documentId,
    }: {
        formData?: IApiRequest;
        documentId: number;
    }): Promise<IApiResponse> => {
        return baseConnector.patch<IApiResponse>(`/api/document/${documentId}/`, formData);
    };

    const deleteDocument = async (id: number) => {
        return baseConnector.remove(`/api/document/${id}`);
    };

    const saveImageDocument = async ({
        formData,
        documentId,
    }: {
        formData: IRawImage;
        documentId: number;
    }) => {
        const blob = formData?.blob;
        if (!blob || blob.size === 0) {
            throw new Error(
                '[useModuleDocumentConnector/saveImageDocument]: Image blob is required',
            );
        }

        const format = formData?.base64?.format || 'png';
        const fileName = `image.${format}`;
        const mimeType = format === 'jpg' || format === 'jpeg' ? 'image/jpeg' : `image/${format}`;

        const file = new File([blob], fileName, { type: mimeType });

        const formDataToSend = new FormData();
        formDataToSend.append('image', file);

        return baseConnector.post(`/api/document/${documentId}/photo/`, formDataToSend, {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        });
    };
    const deleteImageDocument = async ({ imageId }: { imageId: number }) => {
        return baseConnector.remove('/api/document/photo/' + imageId);
    };

    return {
        getDocuments,
        saveDocument,
        updateDocument,
        deleteDocument,
        deleteImageDocument,
        saveImageDocument,
    };
}
