package huaweicloudaad

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

	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/global"
	hwaadmodelv1 "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/aad/v1/model"
	hwaadregion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/aad/v1/region"
	hwaadmodelv2 "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/aad/v2/model"
	"github.com/samber/lo"

	hwaadv1 "github.com/certimate-go/certimate/pkg/sdk3rd-trimmed/github.com/huaweicloud/huaweicloud-sdk-go-v3/services/aad/v1"
	hwaadv2 "github.com/certimate-go/certimate/pkg/sdk3rd-trimmed/github.com/huaweicloud/huaweicloud-sdk-go-v3/services/aad/v2"

	"github.com/certimate-go/certimate/pkg/core"
	xcerthostname "github.com/certimate-go/certimate/pkg/utils/cert/hostname"
	xloop "github.com/certimate-go/certimate/pkg/utils/loop"
)

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

type DeployerConfig struct {
	// 华为云 AccessKeyId。
	AccessKeyId string `json:"accessKeyId"`
	// 华为云 SecretAccessKey。
	SecretAccessKey string `json:"secretAccessKey"`
	// 华为云企业项目 ID。
	EnterpriseProjectId string `json:"enterpriseProjectId,omitempty"`
	// 华为云区域。
	Region string `json:"region"`
	// DDoS 高防实例 ID。
	InstanceId string `json:"instanceId"`
	// 域名匹配模式。
	// 零值时默认值 [DOMAIN_MATCH_PATTERN_EXACT]。
	DomainMatchPattern string `json:"domainMatchPattern,omitempty"`
	// 网站域名（支持泛域名）。
	Domain string `json:"domain"`
}

type Deployer struct {
	config     *DeployerConfig
	logger     *slog.Logger
	sdkClients *wSDKClients
}

var _ Provider = (*Deployer)(nil)

type wSDKClients struct {
	AADv1 *hwaadv1.AadClient
	AADv2 *hwaadv2.AadClient
}

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

	clients, err := createSDKClients(config.AccessKeyId, config.SecretAccessKey, config.Region)
	if err != nil {
		return nil, fmt.Errorf("could not create client: %w", err)
	}

	return &Deployer{
		config:     config,
		logger:     slog.Default(),
		sdkClients: clients,
	}, nil
}

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

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

	// 获取待部署的域名列表
	var domainIds []string
	switch d.config.DomainMatchPattern {
	case "", DOMAIN_MATCH_PATTERN_EXACT:
		{
			if d.config.Domain == "" {
				return nil, fmt.Errorf("config `domain` is required")
			}

			domainCandidates, err := d.getAllDomainsByInstanceId(ctx, d.config.InstanceId)
			if err != nil {
				return nil, err
			}

			domains := lo.Filter(domainCandidates, func(domainItem *hwaadmodelv2.InstanceDomainItem, _ int) bool {
				return d.config.Domain == lo.FromPtr(domainItem.DomainName)
			})
			if len(domains) == 0 {
				return nil, fmt.Errorf("could not find domain")
			}

			domainIds = lo.Map(domains, func(domainItem *hwaadmodelv2.InstanceDomainItem, _ int) string {
				return lo.FromPtr(domainItem.DomainId)
			})
		}

	case DOMAIN_MATCH_PATTERN_WILDCARD:
		{
			if d.config.Domain == "" {
				return nil, fmt.Errorf("config `domain` is required")
			}

			domainCandidates, err := d.getAllDomainsByInstanceId(ctx, d.config.InstanceId)
			if err != nil {
				return nil, err
			}

			domains := lo.Filter(domainCandidates, func(domainItem *hwaadmodelv2.InstanceDomainItem, _ int) bool {
				return xcerthostname.IsMatch(d.config.Domain, lo.FromPtr(domainItem.DomainName))
			})
			if len(domains) == 0 {
				return nil, fmt.Errorf("could not find any domains matched by wildcard")
			}

			domainIds = lo.Map(domains, func(domainItem *hwaadmodelv2.InstanceDomainItem, _ int) string {
				return lo.FromPtr(domainItem.DomainId)
			})
		}

	case DOMAIN_MATCH_PATTERN_CERTSAN:
		{
			domainCandidates, err := d.getAllDomainsByInstanceId(ctx, d.config.InstanceId)
			if err != nil {
				return nil, err
			}

			domains := lo.Filter(domainCandidates, func(domainItem *hwaadmodelv2.InstanceDomainItem, _ int) bool {
				return xcerthostname.IsMatchByCertificatePEM(certPEM, lo.FromPtr(domainItem.DomainName))
			})
			if len(domains) == 0 {
				return nil, fmt.Errorf("could not find any domains matched by certificate")
			}

			domainIds = lo.Map(domains, func(domainItem *hwaadmodelv2.InstanceDomainItem, _ int) string {
				return lo.FromPtr(domainItem.DomainId)
			})
		}

	default:
		return nil, fmt.Errorf("unsupported domain match pattern: '%s'", d.config.DomainMatchPattern)
	}

	// 批量更新域名证书
	if len(domainIds) == 0 {
		d.logger.Info("no aad domains to deploy")
	} else {
		d.logger.Info("found aad domains to deploy", slog.Any("domainIds", domainIds))

		if err := xloop.ForRangeAllWithContext(ctx, domainIds, func(ctx context.Context, domainId string, _ int) error {
			return d.updateDomainCertificate(ctx, domainId, certPEM, privkeyPEM)
		}); err != nil {
			return nil, err
		}
	}

	return &DeployResult{}, nil
}

func (d *Deployer) getAllDomainsByInstanceId(ctx context.Context, cloudInstanceId string) ([]*hwaadmodelv2.InstanceDomainItem, error) {
	domains := make([]*hwaadmodelv2.InstanceDomainItem, 0)

	// 查询实例关联的域名信息
	// REF: https://support.huaweicloud.com/intl/zh-cn/api-aad/ListInstanceDomains.html
	listInstanceDomainsOffset := 0
	listInstanceDomainsLimit := 10
	for {
		select {
		case <-ctx.Done():
			return nil, ctx.Err()
		default:
		}

		listInstanceDomainsReq := &hwaadmodelv2.ListInstanceDomainsRequest{
			InstanceId: cloudInstanceId,
			Offset:     lo.ToPtr(int32(listInstanceDomainsOffset)),
			Limit:      lo.ToPtr(int32(listInstanceDomainsLimit)),
		}
		listInstanceDomainsResp, err := d.sdkClients.AADv2.ListInstanceDomains(listInstanceDomainsReq)
		d.logger.Debug("sdk request 'aad.ListInstanceDomains'", slog.Any("request", listInstanceDomainsReq), slog.Any("response", listInstanceDomainsResp))
		if err != nil {
			return nil, fmt.Errorf("failed to execute sdk request 'aad.ListInstanceDomains': %w", err)
		}

		if listInstanceDomainsResp.Domains == nil {
			break
		}

		ignoredStatuses := []string{"1"}
		for _, domainItem := range *listInstanceDomainsResp.Domains {
			if lo.Contains(ignoredStatuses, lo.FromPtr(domainItem.DomainStatus)) {
				continue
			}

			domains = append(domains, &domainItem)
		}

		if len(*listInstanceDomainsResp.Domains) < listInstanceDomainsLimit {
			break
		}

		listInstanceDomainsOffset += listInstanceDomainsLimit
	}

	return domains, nil
}

func (d *Deployer) updateDomainCertificate(ctx context.Context, cloudDomainId string, certPEM, privkeyPEM string) error {
	// 上传域名对应证书
	// REF: https://support.huaweicloud.com/intl/zh-cn/api-aad/SetCertForDomain.html
	setCertForDomainReq := &hwaadmodelv1.SetCertForDomainRequest{
		Body: &hwaadmodelv1.CertificateBody{
			OpType:      0,
			DomainId:    cloudDomainId,
			CertName:    fmt.Sprintf("certimate_%d", time.Now().UnixMilli()),
			CertFile:    lo.ToPtr(certPEM),
			CertKeyFile: lo.ToPtr(privkeyPEM),
		},
	}
	setCertForDomainResp, err := d.sdkClients.AADv1.SetCertForDomain(setCertForDomainReq)
	d.logger.Debug("sdk request 'aad.SetCertForDomain'", slog.Any("request", setCertForDomainReq), slog.Any("response", setCertForDomainResp))
	if err != nil {
		return fmt.Errorf("failed to execute sdk request 'aad.SetCertForDomain': %w", err)
	}

	return nil
}

func createSDKClients(accessKeyId, secretAccessKey, region string) (*wSDKClients, error) {
	wsdk := &wSDKClients{}

	if region == "" {
		region = "cn-north-4" // AAD 服务默认区域：华北北京四
	}

	{
		auth, err := global.NewCredentialsBuilder().
			WithAk(accessKeyId).
			WithSk(secretAccessKey).
			SafeBuild()
		if err != nil {
			return nil, err
		}

		hcRegion, err := hwaadregion.SafeValueOf(region)
		if err != nil {
			return nil, err
		}

		hcClient, err := hwaadv1.AadClientBuilder().
			WithRegion(hcRegion).
			WithCredential(auth).
			SafeBuild()
		if err != nil {
			return nil, err
		}

		client := hwaadv1.NewAadClient(hcClient)
		wsdk.AADv1 = client
	}

	{
		auth, err := global.NewCredentialsBuilder().
			WithAk(accessKeyId).
			WithSk(secretAccessKey).
			SafeBuild()
		if err != nil {
			return nil, err
		}

		hcRegion, err := hwaadregion.SafeValueOf(region)
		if err != nil {
			return nil, err
		}

		hcClient, err := hwaadv2.AadClientBuilder().
			WithRegion(hcRegion).
			WithCredential(auth).
			SafeBuild()
		if err != nil {
			return nil, err
		}

		client := hwaadv2.NewAadClient(hcClient)
		wsdk.AADv2 = client
	}

	return wsdk, nil
}
