package rainyunrcdn

import (
	"context"
	"fmt"
	"log/slog"
	"strconv"

	"github.com/certimate-go/certimate/pkg/core"
	cmgrimpl "github.com/certimate-go/certimate/pkg/core/certmgr/providers/rainyun-sslcenter"
	rainyunsdk "github.com/certimate-go/certimate/pkg/sdk3rd/rainyun"
)

type (
	Provider     = core.Deployer
	DeployResult = core.DeployerDeployResult
)

type DeployerConfig struct {
	// 雨云 API 密钥。
	ApiKey string `json:"apiKey"`
	// RCDN 实例 ID。
	InstanceId int64 `json:"instanceId"`
	// 域名匹配模式。暂时只支持精确匹配。
	// 零值时默认值 [DOMAIN_MATCH_PATTERN_EXACT]。
	DomainMatchPattern string `json:"domainMatchPattern,omitempty"`
	// 加速域名（支持泛域名）。
	Domain string `json:"domain"`
}

type Deployer struct {
	config     *DeployerConfig
	logger     *slog.Logger
	sdkClient  *rainyunsdk.Client
	sdkCertmgr core.Certmgr
}

var _ Provider = (*Deployer)(nil)

func NewDeployer(config *DeployerConfig) (*Deployer, error) {
	if config == nil {
		return nil, fmt.Errorf("the configuration of the deployer provider is nil")
	}

	client, err := createSDKClient(config.ApiKey)
	if err != nil {
		return nil, fmt.Errorf("could not create client: %w", err)
	}

	pcertmgr, err := cmgrimpl.NewCertmgr(&cmgrimpl.CertmgrConfig{
		ApiKey: config.ApiKey,
	})
	if err != nil {
		return nil, fmt.Errorf("could not create certmgr: %w", err)
	}

	return &Deployer{
		config:     config,
		logger:     slog.Default(),
		sdkClient:  client,
		sdkCertmgr: pcertmgr,
	}, nil
}

func (d *Deployer) SetLogger(logger *slog.Logger) {
	if logger == nil {
		d.logger = slog.New(slog.DiscardHandler)
	} else {
		d.logger = logger
	}

	d.sdkCertmgr.SetLogger(logger)
}

func (d *Deployer) Deploy(ctx context.Context, certPEM, privkeyPEM string) (*DeployResult, error) {
	if d.config.InstanceId == 0 {
		return nil, fmt.Errorf("config `instanceId` is required")
	}
	if d.config.Domain == "" {
		return nil, fmt.Errorf("config `domain` is required")
	}

	// 上传证书
	upres, err := d.sdkCertmgr.Upload(ctx, certPEM, privkeyPEM)
	if err != nil {
		return nil, fmt.Errorf("failed to upload certificate file: %w", err)
	} else {
		d.logger.Info("ssl certificate uploaded", slog.Any("result", upres))
	}

	// RCDN SSL 绑定域名
	// REF: https://api.rainyun.com/#/paths/product-rcdn-instance-:id-ssl_bind/post
	certIdAsInt, _ := strconv.ParseInt(upres.CertId, 10, 64)
	rcdnInstanceSslBindReq := &rainyunsdk.RcdnInstanceSslBindRequest{
		CertId:  certIdAsInt,
		Domains: []string{d.config.Domain},
	}
	rcdnInstanceSslBindResp, err := d.sdkClient.RcdnInstanceSslBindWithContext(ctx, d.config.InstanceId, rcdnInstanceSslBindReq)
	d.logger.Debug("sdk request 'rcdn.InstanceSslBind'", slog.Int64("params.instanceId", d.config.InstanceId), slog.Any("request", rcdnInstanceSslBindReq), slog.Any("response", rcdnInstanceSslBindResp))
	if err != nil {
		return nil, fmt.Errorf("failed to execute sdk request 'rcdn.InstanceSslBind': %w", err)
	}

	return &DeployResult{}, nil
}

func createSDKClient(apiKey string) (*rainyunsdk.Client, error) {
	client, err := rainyunsdk.NewClient(
		rainyunsdk.WithApiKey(apiKey),
	)
	if err != nil {
		return nil, err
	}

	return client, nil
}
