import { ref } from "vue";
import { useQuasar } from "quasar";
import type { AdminMfaPayload, ResponseResult } from "../../../models/AuthModels";
import { useMfaVerification } from "../../composables/useMfaVerification";

type AdminActionResult = ResponseResult<unknown>;

export function useAdminActions(reload?: () => Promise<void>) {
    const $q = useQuasar();
    const actionBusy = ref("");
    const { runMfaAction } = useMfaVerification();

    async function runWithState(
        key: string,
        action: (mfa?: AdminMfaPayload) => Promise<AdminActionResult>,
        successMessage = "操作完成",
    ) {
        actionBusy.value = key;
        try {
            const result = await runMfaAction(action);
            if (!result.success) {
                $q.notify({ type: "negative", message: result.message ?? "操作失败" });
                return false;
            }
            $q.notify({
                type: "positive",
                message: result.message ?? successMessage,
            });
            await reload?.();
            return true;
        } catch (error) {
            $q.notify({
                type: "negative",
                message: error instanceof Error ? error.message : "操作失败",
            });
            return false;
        } finally {
            actionBusy.value = "";
        }
    }

    return {
        actionBusy,
        runWithState,
    };
}
评论加载中...