"use client";

import { useCallback } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "@/core/api";
import { accountService } from "@/features/account/api/account.api";
import {
  addressFormSchema,
  addressFormToRequest,
  type AddressFormData,
} from "@customer-portal/domain/customer";
import { useZodForm } from "@/shared/hooks";

export function useAddressEdit(initial: AddressFormData) {
  const queryClient = useQueryClient();

  const handleSave = useCallback(
    async (formData: AddressFormData) => {
      const requestData = addressFormToRequest(formData);
      await accountService.updateAddress(requestData);
      // Address changes can affect server-personalized services results (eligibility).
      await queryClient.invalidateQueries({ queryKey: queryKeys.services.all() });
    },
    [queryClient]
  );

  return useZodForm({
    schema: addressFormSchema,
    initialValues: initial,
    onSubmit: handleSave,
  });
}
