'use client'
import { useMutation } from '@tanstack/react-query'
import { userTypeUpdate } from './schema';
import { toISOIfNotZ } from '@/lib/utils';

const fetchGraphQlUserTypesUpdate = async (record: userTypeUpdate, uuid: string): Promise<{ data: userTypeUpdate | null; status: number }> => {
    console.log('Update test data from local API');
    console.dir({ record })
    record.expiryStarts = record.expiryStarts ? toISOIfNotZ(record.expiryStarts) : undefined;
    record.expiryEnds = record.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined;
    try {
        const res = await fetch(`/api/user-types/update?uuid=${uuid || ''}`, { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(record) });
        if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
        const data = await res.json();
        return { data: data.data, status: res.status }
    } catch (error) { console.error('Error fetching test data:', error); throw error }
};

export function useUpdateUserTypesMutation() {
    return useMutation({
        mutationFn: ({ data, uuid }: { data: userTypeUpdate, uuid: string }) => fetchGraphQlUserTypesUpdate(data, uuid),
        onSuccess: () => { console.log("User types updated successfully") },
        onError: (error) => { console.error("Update user types failed:", error) },
    })
}
