import { useState } from "react";
import { apiForgotPassword } from "../../services/AuthService";
import { handleToastError, customizeToast } from "../../utils";

interface ForgotPasswordData {
  email: string;
}

function useForgotPasswordService() {
  const [loading, setLoading] = useState(false);

  // Forgot Password
  const forgotPasswordAsync = async (data: ForgotPasswordData) => {
    try {
      setLoading(true);
      const response = await apiForgotPassword(data);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        customizeToast(
          response?.data?.message ||
            "If this email exists, a reset link has been sent.",
          "success"
        );
        return {
          success: true,
          data: response?.data,
          message:
            response.data?.message ||
            "If this email exists, a reset link has been sent.",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response?.data?.message || "Failed to send reset link";
          customizeToast(errorMessage, "danger");
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions
      const errorMessage = error?.response?.data?.message || error.toString();
      customizeToast(errorMessage, "danger");
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    forgotPassword: forgotPasswordAsync,
  };
}

export default useForgotPasswordService;

