import { watch } from "vue";
import { usePage } from "@inertiajs/vue3";
import { toast } from "vue-sonner";
import { useTranslations } from "./useTranslations";

/**
 * Surfaces server-side validation errors as a Sonner toast.
 *
 * Inertia keeps the failing page on screen and exposes the validation
 * bag at `page.props.errors`. Form components show inline errors next
 * to each field already, but a top-of-page toast makes the failure
 * obvious — especially when the offending field is below the fold or
 * inside a Sheet / Dialog.
 *
 * The watcher fingerprints the full error bag so a fresh failure
 * (different errors, or the same errors re-submitted) always pops a
 * new toast. Identical consecutive states are skipped.
 */
export function useValidationErrorToast(): void {
  const page = usePage<{ errors?: Record<string, string> }>();
  const { t } = useTranslations();

  let lastKey = "";

  watch(
    () => {
      const errs = page.props?.errors;
      if (!errs || typeof errs !== "object") return "";
      const keys = Object.keys(errs);
      if (keys.length === 0) return "";
      return JSON.stringify(errs);
    },
    (key) => {
      if (!key) {
        lastKey = "";
        return;
      }
      if (key === lastKey) return;
      lastKey = key;

      const errs = (page.props.errors ?? {}) as Record<string, string>;
      const values = Object.values(errs).filter(
        (v): v is string => typeof v === "string" && v !== "",
      );
      const count = values.length;
      if (count === 0) return;

      const first = values[0];
      const headline =
        t("builder.validation.failed") || "Please correct the errors below";

      if (count === 1) {
        toast.error(headline, { description: first });
      } else {
        toast.error(headline, {
          description: `${first} (and ${count - 1} more)`,
        });
      }
    },
    { immediate: true },
  );
}
