package jsonip

import (
	"context"
	"encoding/json"
	"net"

	"dnsupdater/http"
	"dnsupdater/ip/internal"
)

type Service struct {
	url string
}

func New() *Service {
	return &Service{
		url: "https://jsonip.com",
	}
}

func (s Service) Name() string {
	return "jsonip"
}

func (s Service) Lookup(ctx context.Context) (net.IP, error) {
	resp, err := http.Get(ctx, s.url, nil)
	if err != nil {
		return nil, err
	}

	var v struct {
		Ip       string `json:"ip"`
		Location string `json:"geo-ip"`
		Help     string `json:"API Help"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
		return nil, err
	}

	return internal.ParseIP(v.Ip)
}
