import { useMemo } from 'react';
import useSWR, { mutate } from 'swr';
import { formsEndpoints } from '../../endpoints/hr/recruitment/forms';
import { fetcher } from '@/utils/axios';
import { IFormulaire } from '@/shared/types/formulaire';

// ----------------------------------------------------------------------

const swrOptions = {
  revalidateIfStale: true,      
  revalidateOnFocus: false,    
  revalidateOnReconnect: true, 
};

// ----------------------------------------------------------------------
export function useGetAllForms (){
    const url = formsEndpoints.getallForms;

    const { data, isLoading, error, isValidating } = useSWR<IFormulaire[]>(url, fetcher, swrOptions);

    const memorizedValue = useMemo(
        () => ({
            forms: data || [],
            formsLoading: isLoading,
            formsError: error,
            formsValidating: isValidating,
            formsEmpty: !isLoading && !data?.length,
            refetchforms: () => mutate(url), 
        })
        , [data, error, isLoading]
    );

    return memorizedValue;
}

// ----------------------------------------------------------------------
export function useAddForm() {
    const addForm = async (data: IFormulaire) => {
        const url = formsEndpoints.createForm;
        const response = await fetcher(url, 'post', data);
        mutate(formsEndpoints.getallForms);
        return response;
    };

    return { addForm };
}

// ----------------------------------------------------------------------
export function useUpdateForm() {
    const updateForm = async (formId: string, data: IFormulaire) => {
        const url = formsEndpoints.updateForm(formId);
        const response = await fetcher(url, 'put', data);
        mutate(formsEndpoints.getallForms);
        return response;
    };

    return { updateForm };
}

// ----------------------------------------------------------------------
export function useDeleteForm() {
    const deleteForm = async (formId: string) => {
        const url = formsEndpoints.deleteForm(formId);
        const response = await fetcher(url, 'delete');
        mutate(formsEndpoints.getallForms);
        return response;
    };

    return { deleteForm };
}