// Copyright F3 Authors
// SPDX-License-Identifier: MIT

package http

import (
	"bytes"
	"crypto/tls"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

type Implementation struct {
	newMigrationHTTPClient NewMigrationHTTPClientFun
	skipTLSVerify          *bool
	proxy                  *string
}

type retryIfTooMany struct {
	transport *http.Transport
}

func (o *retryIfTooMany) RoundTrip(req *http.Request) (*http.Response, error) {
	var body []byte
	var err error
	if req.Body != nil {
		body, err = io.ReadAll(req.Body)
		if err != nil {
			return nil, err
		}
	}
	for {
		if body != nil {
			req.Body = io.NopCloser(bytes.NewReader(body))
		}
		resp, err := o.transport.RoundTrip(req)
		if err != nil {
			return resp, err
		}
		if resp.StatusCode != 429 {
			return resp, nil
		}

		wait := 1
		if retryAfter := resp.Header.Get("Retry-After"); retryAfter != "" {
			if v, err := strconv.Atoi(retryAfter); err == nil {
				wait = v
			}
		}
		time.Sleep(time.Duration(wait) * time.Second)
	}
}

func (o *Implementation) GetNewMigrationHTTPClient() NewMigrationHTTPClientFun {
	if o.newMigrationHTTPClient == nil {
		return func() *http.Client {
			transport := &http.Transport{}
			if o.GetSkipTLSVerify() {
				transport.TLSClientConfig = &tls.Config{
					InsecureSkipVerify: true,
				}
			}
			if o.GetProxy() != "" {
				proxyURL, err := url.Parse(o.GetProxy())
				if err != nil {
					panic(fmt.Errorf("url.Parse %w", err))
				}
				transport.Proxy = func(req *http.Request) (*url.URL, error) {
					return http.ProxyURL(proxyURL)(req)
				}
			}
			return &http.Client{
				Transport: &retryIfTooMany{transport},
			}
		}
	}
	return o.newMigrationHTTPClient
}

func (o *Implementation) SetNewMigrationHTTPClient(fun NewMigrationHTTPClientFun) {
	o.newMigrationHTTPClient = fun
}

func (o *Implementation) GetSkipTLSVerify() bool {
	if o.skipTLSVerify == nil {
		return false
	}
	return *o.skipTLSVerify
}

func (o *Implementation) SetSkipTLSVerify(skipTLSVerify bool) {
	o.skipTLSVerify = &skipTLSVerify
}

func (o *Implementation) GetProxy() string {
	if o.proxy == nil {
		return ""
	}
	return *o.proxy
}

func (o *Implementation) SetProxy(proxy string) {
	o.proxy = &proxy
}
