import { useApiMutation, useApiQuery } from "@ema-platform/api";
import { twoFactorRequest } from "./two-factor-request";

type AccountConfig = { id: string; isMFARequired: boolean };

/** Reads and writes the signed-in user's IAM two-step verification setting. */
export function useTwoFactor() {
  const { data, refetch, isLoading } = useApiQuery<{ items: AccountConfig[] }>({
    url: "/account-configurations/my-config",
  });
  const [save, { isLoading: isSaving }] = useApiMutation();

  const config = data?.items?.[0];

  const setEnabled = async (isMFARequired: boolean) => {
    await save(twoFactorRequest(config, isMFARequired)).unwrap();
    await refetch();
  };

  return { enabled: !!config?.isMFARequired, isLoading, isSaving, setEnabled };
}
