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

const fetchGraphQlBuildUpdate = async (record: BuildUpdate, uuid: string, refetchTable: () => void): Promise<{ data: any | null; status: number }> => {
    console.log('Fetching test data from local API');
    record.info.buildDate = toISOIfNotZ(record.info.buildDate);
    record.info.decisionPeriodDate = toISOIfNotZ(record.info.decisionPeriodDate);
    try {
        const res = await fetch(`/api/builds/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(); refetchTable();
        return { data: data.data, status: res.status }
    } catch (error) { console.error('Error fetching test data:', error); throw error }
};

export function useUpdateBuildMutation() {
    return useMutation({
        mutationFn: ({ data, uuid, refetchTable }: { data: BuildUpdate, uuid: string, refetchTable: () => void }) => fetchGraphQlBuildUpdate(data, uuid, refetchTable),
        onSuccess: () => { console.log("Build updated successfully") },
        onError: (error) => { console.error("Update Build failed:", error) },
    })
}
