"use client";

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

export function useProfileEdit(initial: ProfileEditFormData) {
  const handleSave = useCallback(async (formData: ProfileEditFormData) => {
    const requestData: UpdateCustomerProfileRequest = profileFormToRequest(formData);
    const updated = await accountService.updateProfile(requestData);

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

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