/**
 * use-template-generation-actions.ts
 *
 * 模板生成记录的增删改查操作 Hooks
 *
 * 提供功能：
 * - useDeleteGeneration: 删除单个生成记录
 * - useBatchDeleteGenerations: 批量删除生成记录
 */

import { root } from '@repo/core'
import { TemplateGenerationController } from '@repo/sdk'
import { useCallback, useState } from 'react'

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

/**
 * 删除单个生成记录的 Hook
 *
 * @example
 * ```tsx
 * const { deleteGeneration, loading, error } = useDeleteGeneration()
 *
 * const handleDelete = async (id: string) => {
 *   const { data, error } = await deleteGeneration(id)
 *   if (error) {
 *     Alert.alert('错误', error.message)
 *   } else {
 *     Alert.alert('成功', data.message)
 *     refetch() // 刷新列表
 *   }
 * }
 * ```
 */
export const useDeleteGeneration = () => {
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<ApiError | null>(null)

    const deleteGeneration = useCallback(async (id: string) => {
        setLoading(true)
        setError(null)

        const templateGeneration = root.get(TemplateGenerationController)
        const { data, error } = await handleError(
            async () => await templateGeneration.delete({ id }),
        )

        setLoading(false)

        if (error) {
            setError(error)
            return { data: null, error }
        }

        return { data, error: null }
    }, [])

    return {
        deleteGeneration,
        loading,
        error,
    }
}

/**
 * 批量删除生成记录的 Hook
 *
 * @example
 * ```tsx
 * const { batchDeleteGenerations, loading, error } = useBatchDeleteGenerations()
 *
 * const handleBatchDelete = async (ids: string[]) => {
 *   const { data, error } = await batchDeleteGenerations(ids)
 *   if (error) {
 *     Alert.alert('错误', error.message)
 *   } else {
 *     Alert.alert('成功', `已删除 ${data.deletedCount} 条记录`)
 *     refetch() // 刷新列表
 *   }
 * }
 * ```
 */
export const useBatchDeleteGenerations = () => {
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<ApiError | null>(null)

    const batchDeleteGenerations = useCallback(async (ids: string[]) => {
        setLoading(true)
        setError(null)

        const templateGeneration = root.get(TemplateGenerationController)
        const { data, error } = await handleError(
            async () => await templateGeneration.batchDelete({ ids }),
        )

        setLoading(false)

        if (error) {
            setError(error)
            return { data: null, error }
        }

        return { data, error: null }
    }, [])

    return {
        batchDeleteGenerations,
        loading,
        error,
    }
}
