export type ActionState<T> = {
    data?: T;
    error?: string;
    fieldErrors?: Record<string, string[]>;
};

/**
 * Wraps a server action with safe error handling.
 * Usage:
 * export const myAction = safeAction(async (data: MyData) => { ... });
 */
export async function safeAction<T, R>(
    action: (data: T) => Promise<R>,
    data: T
): Promise<ActionState<R>> {
    try {
        const result = await action(data);
        return { data: result };
    } catch (error: any) {
        console.error("Action Error:", error);
        // In production, you might want to log to a service like Sentry here
        return {
            error: error.message || "An unexpected error occurred.",
        };
    }
}

/**
 * Wraps a server action that doesn't take arguments.
 */
export async function safeActionNoArgs<R>(
    action: () => Promise<R>
): Promise<ActionState<R>> {
    try {
        const result = await action();
        return { data: result };
    } catch (error: any) {
        console.error("Action Error:", error);
        return {
            error: error.message || "An unexpected error occurred.",
        };
    }
}
