package publicIp

import (
	"fmt"
	"io"
	"net/http"
)

func ReadIp() (string, error) {
	ip, err := _readIpFromIpify()
	if err == nil {
		return ip, nil
	}

	ip, err = _readIpFromIdentMe()
	if err == nil {
		return ip, nil
	}

	return "", fmt.Errorf("error getting IP from all services: %v", err)
}

func _readIpFromIpify() (string, error) {
	fmt.Printf("Getting IP address from ipify ...\n")
	resp, err := http.Get("https://api.ipify.org?format=text")

	if err != nil {
		return "", fmt.Errorf("error getting IP from ipify: %v", err)
	}

	defer resp.Body.Close()

	ip, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("error reading IP from ipify: %v", err)
	}

	return string(ip), nil
}

func _readIpFromIdentMe() (string, error) {
	fmt.Printf("Getting IP address from identme ...\n")
	resp, err := http.Get("https://4.ident.me")

	if err != nil {
		return "", fmt.Errorf("error getting IP from identme: %v", err)
	}

	defer resp.Body.Close()

	ip, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("error reading IP from identme: %v", err)
	}

	return string(ip), nil
}
