import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useContext } from 'react';
import { initializeDatabase, runMigrations } from './database.js';
import { useQuery } from '@tanstack/react-query';
export const useInitializedDb = () => {
    return useQuery({
        queryKey: ['db'],
        queryFn: async () => {
            const db = await initializeDatabase();
            await runMigrations(db);
            return db;
        },
        staleTime: Infinity,
        retry: false,
    });
};
const DbContext = createContext(undefined);
export function DbProvider({ children }) {
    const { data: db, isLoading, error } = useInitializedDb();
    if (isLoading || error || !db) {
        return null;
    }
    return _jsx(DbContext.Provider, { value: { db }, children: children });
}
export function useDb() {
    const context = useContext(DbContext);
    if (context === undefined) {
        throw new Error('useDb must be used within a DbProvider');
    }
    return context.db;
}
