package example

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/netip"
	"net/url"
	"strings"

	"github.com/qdm12/ddns-updater/internal/models"
	"github.com/qdm12/ddns-updater/internal/provider/constants"
	"github.com/qdm12/ddns-updater/internal/provider/errors"
	"github.com/qdm12/ddns-updater/internal/provider/headers"
	"github.com/qdm12/ddns-updater/internal/provider/utils"
	"github.com/qdm12/ddns-updater/pkg/publicip/ipversion"
)

type Provider struct {
	domain string
	host   string
	// TODO: remove ipVersion and ipv6Suffix if the provider does not support IPv6.
	// Usually they do support IPv6 though.
	ipVersion  ipversion.IPVersion
	ipv6Suffix netip.Prefix
	username   string
	password   string
}

func New(data json.RawMessage, domain, host string,
	ipVersion ipversion.IPVersion, ipv6Suffix netip.Prefix) (
	provider *Provider, err error) {
	var providerSpecificSettings settings
	err = json.Unmarshal(data, &providerSpecificSettings)
	if err != nil {
		return nil, fmt.Errorf("decoding provider specific settings: %w", err)
	}

	err = validateSettings(providerSpecificSettings, domain, host)
	if err != nil {
		return nil, fmt.Errorf("validating provider specific settings: %w", err)
	}

	return &Provider{
		domain:     domain,
		host:       host,
		ipVersion:  ipVersion,
		ipv6Suffix: ipv6Suffix,
		username:   providerSpecificSettings.Username,
		password:   providerSpecificSettings.Password,
	}, nil
}

// TODO adapt to the provider specific settings.
type settings struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func validateSettings(providerSpecificSettings settings, domain, host string) error {
	// TODO: update this switch to be as restrictive as possible
	// to fail early for the user. Use errors already defined
	// in the internal/provider/errors package, or add your own
	// if really necessary. When returning an error, always use
	// fmt.Errorf (to enforce the caller to use errors.Is()).
	switch {
	case domain == "":
		return fmt.Errorf("%w", errors.ErrDomainNotSet)
	case host == "":
		return fmt.Errorf("%w", errors.ErrHostNotSet)
	// TODO: does the provider support wildcard hosts? If not, disallow * hosts
	// case host == "*":
	// 	return fmt.Errorf("%w", errors.ErrHostWildcard)
	case providerSpecificSettings.Username == "":
		return fmt.Errorf("%w", errors.ErrUsernameNotSet)
	case providerSpecificSettings.Password == "":
		return fmt.Errorf("%w", errors.ErrPasswordNotSet)
	}
	return nil
}

func (p *Provider) String() string {
	// TODO update the name of the provider and add it to the
	// internal/provider/constants package.
	return utils.ToString(p.domain, p.host, constants.Dyn, p.ipVersion)
}

func (p *Provider) Domain() string {
	return p.domain
}

func (p *Provider) Host() string {
	return p.host
}

func (p *Provider) IPVersion() ipversion.IPVersion {
	return p.ipVersion
}

func (p *Provider) IPv6Suffix() netip.Prefix {
	return p.ipv6Suffix
}

func (p *Provider) Proxied() bool {
	return false
}

func (p *Provider) BuildDomainName() string {
	return utils.BuildDomainName(p.host, p.domain)
}

func (p *Provider) HTML() models.HTMLRow {
	return models.HTMLRow{
		Domain: fmt.Sprintf("<a href=\"http://%s\">%s</a>", p.BuildDomainName(), p.BuildDomainName()),
		Host:   p.Host(),
		// TODO: update the provider name and link below
		Provider:  "<a href=\"https://dyn.com/\">Dyn DNS</a>",
		IPVersion: p.ipVersion.String(),
	}
}

// TODO: update this function to match the provider's API
// Ideally add a comment with a link to their API documentation.
// If the provider API allows it, create the record if it does not exist.
func (p *Provider) Update(ctx context.Context, client *http.Client, ip netip.Addr) (newIP netip.Addr, err error) {
	u := url.URL{
		Scheme: "https",
		User:   url.UserPassword(p.username, p.password),
		Host:   "example.com",
		Path:   "/nic/update",
	}
	values := url.Values{}
	values.Set("hostname", utils.BuildURLQueryHostname(p.host, p.domain))
	values.Set("myip", ip.String())
	u.RawQuery = values.Encode()

	request, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
	if err != nil {
		return netip.Addr{}, fmt.Errorf("creating http request: %w", err)
	}
	// TODO: there are other helping functions in the headers package to set request headers
	// if you need them.
	headers.SetUserAgent(request)

	response, err := client.Do(request)
	if err != nil {
		return netip.Addr{}, err
	}
	defer response.Body.Close()

	// TODO handle the encoding of the response body properly. Often it can be JSON,
	// see other provider code for examples on how to decode JSON.
	b, err := io.ReadAll(response.Body)
	if err != nil {
		return netip.Addr{}, fmt.Errorf("reading response body: %w", err)
	}
	s := string(b)

	// TODO handle every possible status codes from the provider API.
	// If undocumented, try them out by sending bogus HTTP requests to see
	// what status codes they return, for example with `curl`.
	if response.StatusCode != http.StatusOK {
		return netip.Addr{}, fmt.Errorf("%w: %d: %s",
			errors.ErrHTTPStatusNotValid, response.StatusCode, utils.ToSingleLine(s))
	}

	// TODO handle every possible response bodies from the provider API.
	// If undocumented, try them out by sending bogus HTTP requests to see
	// what response bodies they return, for example with `curl`.
	switch {
	case strings.HasPrefix(s, constants.Notfqdn):
		return netip.Addr{}, fmt.Errorf("%w", errors.ErrHostnameNotExists)
	case strings.HasPrefix(s, "badrequest"):
		return netip.Addr{}, fmt.Errorf("%w", errors.ErrBadRequest)
	case strings.HasPrefix(s, "good"):
		return ip, nil
	default:
		return netip.Addr{}, fmt.Errorf("%w: %s", errors.ErrUnknownResponse, s)
	}
}
