import { notifications } from "@mantine/notifications";

export async function fetchAndStoreUserName(token: string) {
    if (!token) return;

    try {
        const response = await fetch("/api/customer", {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                 "X-Login-Type": "IB",
                "Authorization": `Bearer ${token}`,
            },
        });

        if (!response.ok) {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Error",
                message: "Internal Server Error",
                autoClose: 5000,
            });
            localStorage.removeItem("remitter_name");
            localStorage.removeItem("remitter_mobile_no");
            return;
        }

        const data = await response.json();
        if (Array.isArray(data) && data.length > 0) {
            const { custname, mobileno } = data[0];
            localStorage.setItem("remitter_name", custname);
            localStorage.setItem("remitter_mobile_no", mobileno);
        }
        return true;
    } catch (error: any) {
        localStorage.removeItem("remitter_name");
        localStorage.removeItem("remitter_mobile_no");
        console.error('Error sending OTP:', error.response?.data || error.message);
        notifications.show({
            withBorder: true,
            color: "red",
            title: "Please try again later",
            message: "Unable to Fetch, Please try again later",
            autoClose: 5000,
        });
        throw error.response?.data || error;
    }
}
