import axiosInstance from "@/utils/axios";
import { create } from "zustand";
import { circuitEndpoints } from "../../endpoints/circuit";
import { DocumentDTO } from "@/shared/types/document";

type CircuitDocumentStore = {
    documents: DocumentDTO[];
    loading: boolean;
    error: string | null;
    uploadDocument: (file: File, circuitId: string) => Promise<void>;
    getCircuitDocuments: (circuitId: string) => Promise<void>;
    downloadDocument: (documentId: number) => Promise<string>;
    deleteDocument: (documentId: number) => Promise<void>;
};

export const useCircuitDocumentStore = create<CircuitDocumentStore>((set, get) => ({
    documents: [],
    loading: false,
    error: null,

    uploadDocument: async (file: File, circuitId: string) => {
        set({ loading: true, error: null });
        try {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('circuitId', circuitId);

            await axiosInstance.post(
                circuitEndpoints.document.upload,
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                }
            );

            await get().getCircuitDocuments(circuitId);
            
            set({ loading: false });
        } catch (error: any) {
            set({
                error: error.message || 'Erreur lors du téléchargement du document',
                loading: false,
            });
            throw error;
        }
    },

    getCircuitDocuments: async (circuitId: string) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get<DocumentDTO[]>(
                circuitEndpoints.document.getAll(circuitId)
            );
            set({
                documents: response.data,
                loading: false,
            });
        } catch (error: any) {
            set({
                error: error.message || 'Erreur lors de la récupération des documents',
                loading: false,
            });
            throw error;
        }
    },

    downloadDocument: async (documentId: number) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get(
                circuitEndpoints.document.download(documentId),
                { responseType: 'blob' }
            );
            const blob = new Blob([response.data]);
            const downloadUrl = window.URL.createObjectURL(blob);
            
            set({ loading: false });
            return downloadUrl;
        } catch (error: any) {
            set({
                error: error.message || "Erreur lors du téléchargement du document",
                loading: false,
            });
            throw error;
        }
    },
    deleteDocument: async (documentId: number) => {
        set({ loading: true, error: null });
        try {
            await axiosInstance.delete(
                circuitEndpoints.document.delete(documentId)
            );

            set((state) => ({
                documents: state.documents.filter((doc) => doc.id !== documentId),
                loading: false,
            }));
        } catch (error: any) {
            set({
                error: error.message || "Erreur lors de la suppression du document",
                loading: false,
            });
            throw error;
        }
    },

}));
