// AUTO-GENERATED by mizan — do not edit

import { ref, computed, onMounted, onUnmounted, onServerPrefetch, type ComputedRef } from 'vue'
import { registerContext, type ContextState } from '@mizan/base'

{% if !stage1_imports.is_empty() -%}
import { {{ stage1_imports|join(", ") }} } from '../index'

{% endif -%}
{% for ctx in contexts -%}
export function use{{ ctx.pascal }}Context({% if ctx.has_params %}params: {{ ctx.pascal }}ContextParams{% endif %}) {
    const state = ref<ContextState<{{ ctx.pascal }}ContextData>>({ data: null, status: 'idle', error: null })
    let handle: ReturnType<typeof registerContext> | null = null

    onMounted(() => {
        handle = registerContext('{{ ctx.name }}', {{ ctx.params_arg }}, () => fetch{{ ctx.pascal }}Context({{ ctx.params_arg }}))
        handle.subscribe(() => { state.value = handle!.getState() })
        handle.refetch()
    })

    onServerPrefetch(async () => {
        handle = registerContext('{{ ctx.name }}', {{ ctx.params_arg }}, () => fetch{{ ctx.pascal }}Context({{ ctx.params_arg }}))
        await handle.refetch()
        state.value = handle.getState()
    })

    onUnmounted(() => { handle?.unregister() })

    return {
        state,
{%- for fn in ctx.fns %}
        {{ fn.camel_name }}: computed(() => state.value.data?.{{ fn.name }} ?? null) as ComputedRef<{{ fn.output_type }} | null>,
{%- endfor %}
        loading: computed(() => state.value.status === 'loading'),
        error: computed(() => state.value.error),
    }
}

{% endfor -%}
{% for call in calls -%}
export function use{{ call.pascal }}() {
    const isPending = ref(false)
    const error = ref<Error | null>(null)
{%- if call.has_input %}
    async function mutate(args: Parameters<typeof call{{ call.pascal }}>[0]) {
        isPending.value = true; error.value = null
        try { return await call{{ call.pascal }}(args) }
        catch (e) { error.value = e as Error; throw e }
        finally { isPending.value = false }
    }
{%- else %}
    async function mutate() {
        isPending.value = true; error.value = null
        try { return await call{{ call.pascal }}() }
        catch (e) { error.value = e as Error; throw e }
        finally { isPending.value = false }
    }
{%- endif %}
    return { mutate, isPending, error }
}

{% endfor -%}
export type { ContextState } from '@mizan/base'
export { configure, initSession, MizanError } from '@mizan/base'

