import type {IUserAddresses} from "@/types/user-addresses-d-t";
import type {IUserAddressesResponse} from "@/types/user-addresses-response-d-t";

export async function userAddressesData({
                                            id=undefined,
                                            plain = false,
                                            pagination = false,
                                            page = 1
}: {
    id?: string|number;
    plain?: boolean;
    pagination?: boolean;
    page?: number;
} = {}): Promise<IUserAddresses[]|IUserAddressesResponse[]> {
    try {
        let query = id ? `/${id}` : '';
        const response = await $axios.get(`addresses${query}?page=${page}`);

        if (plain) {
            if (pagination) {
                return (response?.data || []) as IUserAddressesResponse[];
            }

            return (response?.data?.data || []) as IUserAddresses[];
        }

        const data = response?.data?.data || [];
        return (Array.isArray(data) && data || [data]).map(convertUserAddressesResponse);
    } catch (error) {
        console.error('Error fetching user addressess data:', error);
        return [] as IUserAddresses[];
    }
}

export function convertUserAddressesResponse(data: IUserAddressesResponse): IUserAddresses {
    return {
        ...data,
        long: Number(data?.long || 0),
        lat: Number(data?.lat || 0),
    };
}

export default userAddressesData;
