import axiosInstance from "@/utils/axios";
import { create } from "zustand";
import { DocumentDTO } from "@/shared/types/document";
import { documentEndpoints } from "@/shared/api/endpoints/document-service";

type DocumentStore = {
    documents: DocumentDTO[];
    document: DocumentDTO | null;
    loading: boolean;
    error: string | null;
    upload: (file: File, userId: string) => Promise<number>;
    getUserDocuments: (ownerUuid: string) => Promise<void>;
    deleteDocument: (ownerId: number, documentId: number) => Promise<void>;
    getDocumentById: (docId: number, userId: number) => Promise<DocumentDTO | null>;
    renameDocument: (ownerId: string, documentId: number, newName: string) => Promise<void>;
};

export const useDocumentStore = create<DocumentStore>((set) => ({
    documents: [],
    document: null,
    loading: false,
    error: null,

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

            const response = await axiosInstance.post<number>(
                documentEndpoints.Document.upload,
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                }
            );
            set((state) => ({
                documents: [...state.documents],
                loading: false,
            }));
            return response.data;
        } catch (error: any) {
            set({
                error: error.message || 'Erreur lors du téléchargement du document',
                loading: false,
            });
            throw error;
        }
    },
    getDocumentById: async (docId: number, userId: number) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get<DocumentDTO>(
                documentEndpoints.Document.getByIdAbDriver(docId, userId)
            );
            set({
                document: response.data,
                loading: false,
            });
            console.log("Document retrieved:", response.data);
            
            return response.data;
        } catch (error: any) {
            set({
                error: error.message || 'Erreur lors de la récupération du document',
                loading: false,
            });
            throw error;
        }
    },

    getUserDocuments: async (ownerUuid: string) => {
        set({ loading: true, error: null });
        try {
            const response = await axiosInstance.get<DocumentDTO[]>(
                documentEndpoints.Document.getUserDocuments(ownerUuid)
            );
            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
        }
    },

    deleteDocument: async (ownerId: number, documentId: number) => {
        set({ loading: true, error: null })
        try {
            await axiosInstance.delete(documentEndpoints.Document.delete(ownerId, 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
        }
    },
    renameDocument: async (ownerId: string, documentId: number, newName: string) => {
        set({ loading: true, error: null })
        try {
            await axiosInstance.post(documentEndpoints.Document.renameDocument(ownerId, documentId, newName))
            set({ loading: false })
        } catch (error: any) {
            set({
                error: error.message || "Erreur lors de la modification du nom du document",
                loading: false,
            })
            throw error
        }
    },

}))
