import React, { createContext, useContext } from 'react';

export type ModelInstance<T> = {
    Provider: React.FC<{ children: React.ReactNode }>;
    useModel: () => T;
    namespace: string;
};

export function createModel<T>(useHook: () => T, namespace: string): ModelInstance<T> {
    const Context = createContext<T | null>(null);

    const Provider = ({ children }: { children: React.ReactNode }) => {
        const value = useHook();
        return <Context.Provider value={value}>{children}</Context.Provider>;
    };

    const useModel = () => {
        const context = useContext(Context);
        if (!context) throw new Error(`Model '${namespace}' must be used inside its Provider`);
        return context;
    };

    return { Provider, useModel, namespace };
}
