"use client"

import { useMutation, type UseMutationOptions } from "@tanstack/react-query"
import type { FieldValues, UseFormReturn } from "react-hook-form"
import { ApiError } from "@garage/api"
import { useDialogClose } from "./use-dialog-close"

export function useFormMutation<TValues extends FieldValues, TResponse = unknown>(
    form: UseFormReturn<TValues>,
    options: UseMutationOptions<TResponse, Error, TValues>,
) {
    const closeDialog = useDialogClose()

    return useMutation<TResponse, Error, TValues>({
        ...options,
        onSuccess: async (data, vars, onMutateResult, ctx) => {
            await options.onSuccess?.(data, vars, onMutateResult, ctx)
            // If this form is rendered inside a dialog wrapper that registers
            // a close handler (e.g. FormDialog), dismiss the dialog after a
            // successful submit. Plain pages render the form without the
            // provider, so this is a no-op there.
            closeDialog?.()
        },
        onError: (err, vars, values, ctx) => {
            if (err instanceof ApiError && err.validationErrors) {
                Object.entries(err.validationErrors).forEach(([field, msgs]) => {
                    form.setError(field as any, { message: msgs[0] })
                })
            }
            options.onError?.(err, vars, values, ctx,)
        },
    })
}
