// Copyright Earl Warren <contact@earl-warren.org>
// Copyright Loïc Dachary <loic@dachary.org>
// Copyright twenty-panda <twenty-panda@posteo.com>
// SPDX-License-Identifier: MIT

package http

import (
	"crypto/tls"
	"fmt"
	"net/http"
	"net/url"
)

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

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: 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
}
