import type { FormikProps } from "formik";
import {
  scrollToFirstError,
  type ErrorFieldSelectors,
} from "@/features/shared/scrollToFirstError";
import type { VolunteerFormValues } from "./volunteerFormTypes";

type Bag = Pick<
  FormikProps<VolunteerFormValues>,
  "values" | "setTouched" | "validateForm" | "submitForm"
>;

/**
 * What the Publish button does before anything is sent.
 *
 * Formik only marks a field touched once it has been visited, so a field the
 * organizer never scrolled to would fail validation silently. Everything is
 * marked touched first, then validated; a failure scrolls to the offending
 * field rather than leaving the button looking unresponsive.
 */
export function buildVolunteerSubmitClick(
  { values, setTouched, validateForm, submitForm }: Bag,
  errorFieldSelectors: ErrorFieldSelectors
) {
  return async () => {
    const touchedFields = Object.keys(values).reduce(
      (acc, field) => {
        acc[field] = true;
        return acc;
      },
      {} as Record<string, boolean>
    );
    setTouched(touchedFields);

    const validationErrors = await validateForm();
    if (Object.keys(validationErrors).length > 0) {
      scrollToFirstError(validationErrors, errorFieldSelectors);
      return;
    }
    submitForm();
  };
}
