import { useI18n } from "vue-i18n";

/**
 * Confirmación SweetAlert2 + DELETE con mensaje 422 del backend.
 * @param {{ label: string, onDelete: () => Promise<unknown>, onSuccess?: () => void|Promise<void> }} opts
 * @returns {Promise<boolean>}
 */
export function useConfirmDelete() {
  const { t } = useI18n();

  async function confirmDelete({ label, onDelete, onSuccess }) {
    const Swal = window.Swal;
    if (!Swal) return false;

    const result = await Swal.fire({
      title: t("common.delete_title"),
      text: t("common.delete_text", { name: label }),
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#d33",
      confirmButtonText: t("common.delete_yes"),
      cancelButtonText: t("common.delete_no"),
    });

    if (!result.isConfirmed) return false;

    try {
      await onDelete();
      await onSuccess?.();
      return true;
    } catch (err) {
      const msg = err?.response?.data?.message || t("common.delete_error");
      await Swal.fire({ icon: "error", title: msg });
      return false;
    }
  }

  return { confirmDelete };
}
