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

const fetchGraphQlBuildAdd = async (record: BuildAdd): Promise<{ data: BuildAdd | 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);
    console.dir({ record })
    try {
        const res = await fetch('/api/builds/add', { 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 useAddBuildMutation() {
    return useMutation({
        mutationFn: ({ data }: { data: BuildAdd }) => fetchGraphQlBuildAdd(data),
        onSuccess: () => { console.log("Build created successfully") },
        onError: (error) => { console.error("Add build failed:", error) },
    })
}
