'use client'
import { useMutation } from '@tanstack/react-query'
import { UserAdd } from './types'
import { toISOIfNotZ } from '@/lib/utils'

const fetchGraphQlUsersAdd = async (
    record: UserAdd,
    selectedBuildIDS: string[],
    selectedCompanyIDS: string[],
    defaultSelection: string,
    refetchTable: () => void
): Promise<{ data: UserAdd | null; status: number }> => {
    record.expiryStarts = toISOIfNotZ(record.expiryStarts);
    record.expiryEnds = toISOIfNotZ(record.expiryEnds);
    try {
        const res = await fetch('/api/users/add', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify({ ...record, selectedBuildIDS, selectedCompanyIDS, defaultSelection }) });
        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 useAddUserMutation() {
    return useMutation({
        mutationFn: (
            { data, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable }: { data: UserAdd, selectedBuildIDS: string[], selectedCompanyIDS: string[], defaultSelection: string, refetchTable: () => void }
        ) => fetchGraphQlUsersAdd(data, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable),
        onSuccess: () => { console.log("User created successfully") },
        onError: (error) => { console.error("Create user failed:", error) },
    })
}
