import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import api from "@/lib/axios";
import { toast } from "sonner";

export interface ChatbotSetting {
    id?: number;
    whatsapp_account_id?: number;
    is_active: boolean;
    chatbot_reset_days: number;
    is_testing_mode: boolean;
    test_phone_numbers: string | null;
    is_out_of_office_active: boolean;
    is_out_of_office_testing_mode: boolean;
    out_of_office_test_phone_numbers: string | null;
    out_of_office_delay_minutes: number;
    out_of_office_cooldown_hours: number;
    chatbot_greeting_message: string | null;
    chatbot_product_message: string | null;
    chatbot_location_message: string | null;
    chatbot_handoff_message: string | null;
    out_of_office_message: string | null;
    out_of_office_message_new_customer: string | null;
    business_hours: any;
}

export const useChatbotSettings = () => {
    const accountId = process.env.NEXT_PUBLIC_APP_ACCOUNT_ID_WHATSAPP_SERVICE;
    
    return useQuery({
        queryKey: ["chatbot-settings", accountId],
        queryFn: async () => {
            const response = await api.get<ChatbotSetting>(`/api/whatsapp/chatbot-settings`, {
                headers: {
                    'whatsapp-account-id': accountId
                }
            });
            return response.data;
        },
        enabled: !!accountId
    });
};

export const useUpdateChatbotSettings = () => {
    const queryClient = useQueryClient();
    const accountId = process.env.NEXT_PUBLIC_APP_ACCOUNT_ID_WHATSAPP_SERVICE;

    return useMutation({
        mutationFn: async (data: Partial<ChatbotSetting>) => {
            const response = await api.post(`/api/whatsapp/chatbot-settings`, {
                whatsapp_account_id: accountId,
                ...data
            });
            return response.data;
        },
        onSuccess: () => {
             queryClient.invalidateQueries({ queryKey: ["chatbot-settings", accountId] });
             toast.success("Pengaturan Chatbot berhasil disimpan");
        },
        onError: (error: any) => {
             toast.error(error?.response?.data?.message || "Failed to update settings");
        }
    });
};
