import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import * as api from '../service/DraftService';
import { MessageListQueryDto, DraftUpdateDto } from '../types/DraftTypes';

export const useGetDrafts = (query: MessageListQueryDto) => {
    return useQuery({
        queryKey: ['drafts', query],
        queryFn: () => api.getDrafts(query),
        staleTime: 0
    });
};

export const useGetDraftDetail = (messageId: string, enabled: boolean = true) => {
    return useQuery({
        queryKey: ['draft', messageId],
        queryFn: () => api.getDraftDetail(messageId),
        enabled: !!messageId && enabled,
        staleTime: 0
    });
};

export const useDeleteDraft = () => {
    const queryClient = useQueryClient();

    return useMutation({
        mutationFn: (messageId: string) => api.deleteDraft(messageId),
        onSuccess: () => {
            // Invalidate drafts queries to refresh the list
            queryClient.invalidateQueries({ queryKey: ['drafts'] });
        },
    });
};

export const useEditDraft = () => {
    const queryClient = useQueryClient();

    return useMutation({
        mutationFn: ({ messageId, draftData }: { messageId: string; draftData: DraftUpdateDto }) =>
            api.editDraft(messageId, draftData),
        onSuccess: () => {
            // Invalidate drafts queries to refresh the list
            queryClient.invalidateQueries({ queryKey: ['drafts'] });
        },
    });
};

export const useUpdateDraft = () => {
    const queryClient = useQueryClient();

    return useMutation({
        mutationFn: ({ messageId, draftData }: { messageId: string; draftData: DraftUpdateDto }) =>
            api.updateDraft(messageId, draftData),
        onSuccess: () => {
            // Invalidate drafts queries to refresh the list
            queryClient.invalidateQueries({ queryKey: ['drafts'] });
        },
    });
};

export const useSendDraft = () => {
    const queryClient = useQueryClient();

    return useMutation({
        mutationFn: (messageId: string) => api.sendDraft(messageId),
        onSuccess: () => {
            // Invalidate drafts queries to refresh the list
            queryClient.invalidateQueries({ queryKey: ['drafts'] });
        },
    });
}; 