import { root } from '@repo/core'
import { type RunTemplateInput, TemplateController } from '@repo/sdk'
import { useCallback, useRef, useState } from 'react'

import { type ApiError } from '@/lib/types'
import { handleError } from './use-error'

export const useTemplateActions = () => {
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<ApiError | null>(null)
    const lastParamsRef = useRef<RunTemplateInput | null>(null)

    const runTemplate = useCallback(async (params: RunTemplateInput): Promise<{ generationId?: string; error?: ApiError }> => {
        setLoading(true)
        setError(null)
        lastParamsRef.current = params

        const template = root.get(TemplateController)
        const { data, error } = await handleError(async () => await template.run({
            templateId: params.templateId,
            data: params.data || {},
        }))

        setLoading(false)

        if (error) {
            setError(error)
            return { error }
        }

        return { generationId: data?.generationId }
    }, [])

    const retry = useCallback(async (): Promise<{ generationId?: string; error?: ApiError }> => {
        if (!lastParamsRef.current) {
            return { error: { message: 'No previous operation to retry' } as ApiError }
        }
        return runTemplate(lastParamsRef.current)
    }, [runTemplate])

    return {
        loading,
        error,
        runTemplate,
        retry,
    }
}
