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

const fetchGraphQlBuildSitesAdd = async (record: BuildPartsAdd, buildId: string, refetchTable: () => void): Promise<{ data: BuildPartsAdd | null; status: number }> => {
    console.log('Fetching test data from local API');
    record.expiryStarts = record.expiryStarts ? toISOIfNotZ(record.expiryStarts) : undefined;
    record.expiryEnds = record.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined;
    try {
        const res = await fetch('/api/builds-parts/add', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ data: record, buildId }) });
        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 useAddBuildAreasMutation() {
    return useMutation({
        mutationFn: ({ data, buildId, refetchTable }: { data: BuildPartsAdd, buildId: string, refetchTable: () => void }) => fetchGraphQlBuildSitesAdd(data, buildId, refetchTable),
        onSuccess: () => { console.log("Build areas created successfully") },
        onError: (error) => { console.error("Add build areas failed:", error) },
    })
}
