import api from '@/utils/api';
import { Directory, File, Paths } from 'expo-file-system';
import * as Sharing from 'expo-sharing';

/**
 * Handles upload of a document through the server using FormData
 * @param file File to upload (must have at least the 'uri' property)
 * @param siteId ID of the site to associate the document with (null for general register)
 * @param customTitle Custom title for the document (optional)
 */
export const uploadDocument = async (
    file: any,
    siteId: number | null,
    customTitle?: string
): Promise<void> => {
    if (!file || !file.uri) {
        throw new Error("File non valido per l'upload.");
    }

    try {
        const formData = new FormData();
        formData.append('file', {
            uri: file.uri,
            name: customTitle || file.name,
            type: file.mimeType
        } as any);

        if (siteId !== null) {
            formData.append('siteId', siteId.toString());
        }

        if (customTitle) {
            formData.append('customTitle', customTitle.trim());
        }

        const response = await api.post('/attachment/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
            }
        });

        console.log("Risposta server:", response.data);

        if (response.data?.status === 'error') {
            throw new Error(response.data.message || "Errore sconosciuto dal server");
        }

    } catch (error: any) {
        console.error("Errore durante l'upload del documento:", error);

        if (error.response) {
            const serverMessage = error.response.data?.message || error.message;
            throw new Error(`Errore Server (${error.response.status}): ${serverMessage}`);
        } else if (error.request) {
            throw new Error("Il server non risponde. Controlla la connessione.");
        } else {
            throw error;
        }
    }
};

/**
 * Download and share a document (expo-sharing)
 * @param attachmentId ID or relative URL of the document
 * @param fileName Name to save the file as
 * @param fileUrl Full URL of the file to download
 */
export const downloadAndShareDocument = async (
    mimetype: string,
    fileName: string,
    fileUrl: string
): Promise<void> => {
    try {
        // TODO: Download based on expo-sharing - some mime types may not be supported     
        if (!fileUrl || !fileName) {
            throw new Error("Parametri mancanti per il download del documento.");
        }

        const destination = new Directory(Paths.cache, 'documents');
        destination.exists ? destination.delete() : null;
        destination.create({ overwrite: true });

        const tmpFile = await File.downloadFileAsync(fileUrl, destination);
        console.log("File temporaneo scaricato in:", tmpFile.uri);

        const outFile = new File(destination, fileName);
        await tmpFile.move(outFile);
        console.log("File spostato in:", outFile.uri);
        console.log("File type:", mimetype);

        if (await Sharing.isAvailableAsync()) {
            await Sharing.shareAsync(outFile.uri, {
                mimeType: mimetype,
                dialogTitle: `Scarica ${fileName}`,
                UTI: 'public.item'
            });
        } else {
            throw new Error("Condivisione non supportata su questo dispositivo.");
        }

    } catch (error) {
        console.error("Download Error:", error);
        throw error;
    }
};
