package akamaiedgedns

import (
	"time"

	"github.com/akamai/AkamaiOPEN-edgegrid-golang/v13/pkg/edgegrid"
	"github.com/go-acme/lego/v5/providers/dns/edgedns"

	"github.com/certimate-go/certimate/pkg/core"
)

type ChallengerConfig struct {
	Host                  string
	ClientToken           string
	ClientSecret          string
	AccessToken           string
	DnsPropagationTimeout int
	DnsTTL                int
}

func NewChallenger(config *ChallengerConfig) (core.ACMEChallenger, error) {
	edgegridConfig := &edgegrid.Config{
		Host:         config.Host,
		ClientToken:  config.ClientToken,
		ClientSecret: config.ClientSecret,
		AccessToken:  config.AccessToken,
		MaxBody:      131072,
		HeaderToSign: []string{
			"X-Akamai-ACS-Action",
			"X-Akamai-ACS-Auth-Data",
			"X-Akamai-ACS-Auth-Sign",
		},
	}

	providerConfig := edgedns.NewDefaultConfig()
	providerConfig.Config = edgegridConfig
	if config.DnsPropagationTimeout > 0 {
		providerConfig.PropagationTimeout = time.Duration(config.DnsPropagationTimeout) * time.Second
	}
	if config.DnsTTL > 0 {
		providerConfig.TTL = config.DnsTTL
	}

	provider, err := edgedns.NewDNSProviderConfig(providerConfig)
	if err != nil {
		return nil, err
	}

	return provider, nil
}
