"use client";

import { useCallback } from "react";
import { accountService } from "@/features/account/api/account.api";
import { useAuthStore } from "@/features/auth/stores/auth.store";
import {
  profileEditFormSchema,
  profileFormToRequest,
  type ProfileEditFormData,
} from "@customer-portal/domain/customer";
import { type UpdateCustomerProfileRequest } from "@customer-portal/domain/auth";
import { useZodForm } from "@/shared/hooks";

export function useProfileEdit(initial: ProfileEditFormData) {
  const handleSave = useCallback(async (formData: ProfileEditFormData) => {
    const previousEmail = useAuthStore.getState().user?.email ?? null;
    const requestData: UpdateCustomerProfileRequest = profileFormToRequest(formData);
    const updated = await accountService.updateProfile(requestData);

    // If email changed, refresh the session immediately to avoid access-token email mismatch
    // triggering an automatic logout (auth guard compares token email vs DB email).
    if (requestData.email && previousEmail && requestData.email !== previousEmail) {
      await useAuthStore.getState().refreshSession();
      // refreshSession already updates user+session in the store.
      return;
    }

    useAuthStore.setState(state => ({
      ...state,
      user: state.user ? { ...state.user, ...updated } : state.user,
    }));
  }, []);

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