package ucloudualb

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

	"github.com/samber/lo"
	"github.com/ucloud/ucloud-sdk-go/services/ulb"
	"github.com/ucloud/ucloud-sdk-go/ucloud"
	"github.com/ucloud/ucloud-sdk-go/ucloud/auth"

	"github.com/certimate-go/certimate/pkg/core"
	cmgrimpl "github.com/certimate-go/certimate/pkg/core/certmgr/providers/ucloud-ulb"
	ucloudsdk "github.com/certimate-go/certimate/pkg/sdk3rd/ucloud/ulb"
	xloop "github.com/certimate-go/certimate/pkg/utils/loop"
)

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

type DeployerConfig struct {
	// 优刻得 API 私钥。
	PrivateKey string `json:"privateKey"`
	// 优刻得 API 公钥。
	PublicKey string `json:"publicKey"`
	// 优刻得项目 ID。
	ProjectId string `json:"projectId,omitempty"`
	// 优刻得地域。
	Region string `json:"region"`
	// 部署目标。
	DeployTarget string `json:"deployTarget"`
	// 负载均衡实例 ID。
	// 部署目标为 [DEPLOY_TARGET_LOADBALANCER]、[DEPLOY_TARGET_LISTENER] 时必填。
	LoadbalancerId string `json:"loadbalancerId,omitempty"`
	// 负载均衡监听器 ID。
	// 部署目标为 [DEPLOY_TARGET_LISTENER] 时必填。
	ListenerId string `json:"listenerId,omitempty"`
	// SNI 域名（不支持泛域名）。
	// 部署目标为 [DEPLOY_TARGET_LISTENER] 时选填。
	Domain string `json:"domain,omitempty"`
}

type Deployer struct {
	config     *DeployerConfig
	logger     *slog.Logger
	sdkClient  *ucloudsdk.ULBClient
	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.PrivateKey, config.PublicKey, config.ProjectId, config.Region)
	if err != nil {
		return nil, fmt.Errorf("could not create client: %w", err)
	}

	pcertmgr, err := cmgrimpl.NewCertmgr(&cmgrimpl.CertmgrConfig{
		PrivateKey: config.PrivateKey,
		PublicKey:  config.PublicKey,
		ProjectId:  config.ProjectId,
		Region:     config.Region,
	})
	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) {
	// 上传证书
	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))
	}

	// 根据部署目标决定业务流程
	switch d.config.DeployTarget {
	case DEPLOY_TARGET_LOADBALANCER:
		if err := d.deployToLoadbalancer(ctx, upres.CertId); err != nil {
			return nil, err
		}

	case DEPLOY_TARGET_LISTENER:
		if err := d.deployToListener(ctx, upres.CertId); err != nil {
			return nil, err
		}

	default:
		return nil, fmt.Errorf("unsupported deploy target '%s'", d.config.DeployTarget)
	}

	return &DeployResult{}, nil
}

func (d *Deployer) deployToLoadbalancer(ctx context.Context, cloudCertId string) error {
	if d.config.LoadbalancerId == "" {
		return fmt.Errorf("config `loadbalancerId` is required")
	}

	// 获取 ALB 下的 HTTPS 监听器列表
	// REF: https://docs.ucloud.cn/api/ulb-api/describe_listeners
	listenerIds := make([]string, 0)
	describeListenersOffset := 0
	describeListenersLimit := 100
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		default:
		}

		describeListenerReq := d.sdkClient.NewDescribeListenersRequest()
		describeListenerReq.LoadBalancerId = ucloud.String(d.config.LoadbalancerId)
		describeListenerReq.Offset = ucloud.Int(describeListenersOffset)
		describeListenerReq.Limit = ucloud.Int(describeListenersLimit)
		describeListenerResp, err := d.sdkClient.DescribeListeners(describeListenerReq)
		d.logger.Debug("sdk request 'ulb.DescribeListeners'", slog.Any("request", describeListenerReq), slog.Any("response", describeListenerResp))
		if err != nil {
			return fmt.Errorf("failed to execute sdk request 'ulb.DescribeListeners': %w", err)
		}

		for _, listenerItem := range describeListenerResp.Listeners {
			if listenerItem.ListenerProtocol == "HTTPS" {
				listenerIds = append(listenerIds, listenerItem.ListenerId)
			}
		}

		if len(describeListenerResp.Listeners) < describeListenersLimit {
			break
		}

		describeListenersOffset += describeListenersLimit
	}

	// 批量更新 Listener 证书
	if len(listenerIds) == 0 {
		d.logger.Info("no alb listeners to deploy")
	} else {
		d.logger.Info("found alb listeners to deploy", slog.Any("listenerIds", listenerIds))

		if err := xloop.ForRangeAllWithContext(ctx, listenerIds, func(ctx context.Context, listenerId string, _ int) error {
			return d.updateListenerCertificate(ctx, d.config.LoadbalancerId, listenerId, cloudCertId)
		}); err != nil {
			return err
		}
	}

	return nil
}

func (d *Deployer) deployToListener(ctx context.Context, cloudCertId string) error {
	if d.config.LoadbalancerId == "" {
		return fmt.Errorf("config `loadbalancerId` is required")
	}
	if d.config.ListenerId == "" {
		return fmt.Errorf("config `listenerId` is required")
	}

	if err := d.updateListenerCertificate(ctx, d.config.LoadbalancerId, d.config.ListenerId, cloudCertId); err != nil {
		return err
	}

	return nil
}

func (d *Deployer) updateListenerCertificate(ctx context.Context, cloudLoadbalancerId, cloudListenerId string, cloudCertId string) error {
	// 描述应用型负载均衡监听器
	// REF: https://docs.ucloud.cn/api/ulb-api/describe_listeners
	describeListenersReq := d.sdkClient.NewDescribeListenersRequest()
	describeListenersReq.LoadBalancerId = ucloud.String(cloudLoadbalancerId)
	describeListenersReq.ListenerId = ucloud.String(cloudListenerId)
	describeListenersReq.Limit = ucloud.Int(1)
	describeListenerResp, err := d.sdkClient.DescribeListeners(describeListenersReq)
	d.logger.Debug("sdk request 'ulb.DescribeListeners'", slog.Any("request", describeListenersReq), slog.Any("response", describeListenerResp))
	if err != nil {
		return fmt.Errorf("failed to execute sdk request 'ulb.DescribeListeners': %w", err)
	} else if len(describeListenerResp.Listeners) == 0 {
		return fmt.Errorf("could not find alb listener '%s'", cloudListenerId)
	}

	listenerInfo := describeListenerResp.Listeners[0]
	if len(listenerInfo.Certificates) > 0 {
		d.logger.Info("found alb listener certificates in used", slog.Any("certificates", listenerInfo.Certificates))
	}

	if d.config.Domain == "" {
		// 未指定 SNI，只需部署到监听器
		if lo.SomeBy(listenerInfo.Certificates, func(item ulb.Certificate) bool { return item.SSLId == cloudCertId && item.IsDefault }) {
			d.logger.Info("no need to deploy alb listener default certificate")
			return nil
		}
		return d.updateListenerDefaultCertificate(ctx, cloudLoadbalancerId, cloudListenerId, cloudCertId)
	} else {
		// 指定 SNI，需部署到扩展域名
		if lo.SomeBy(listenerInfo.Certificates, func(item ulb.Certificate) bool { return item.SSLId == cloudCertId && !item.IsDefault }) {
			d.logger.Info("no need to deploy alb listener sni certificate")
			return nil
		}
		return d.updateListenerSniCertificate(ctx, cloudLoadbalancerId, listenerInfo, cloudCertId)
	}
}

func (d *Deployer) updateListenerDefaultCertificate(ctx context.Context, cloudLoadbalancerId, cloudListenerId string, cloudCertId string) error {
	// 更新应用型负载均衡监听器属性
	// REF: https://docs.ucloud.cn/api/ulb-api/update_listener_attribute_json
	updateListenerAttributeReq := d.sdkClient.NewUpdateListenerAttributeRequest()
	updateListenerAttributeReq.LoadBalancerId = ucloud.String(cloudLoadbalancerId)
	updateListenerAttributeReq.ListenerId = ucloud.String(cloudListenerId)
	updateListenerAttributeReq.Certificates = []string{cloudCertId}
	updateListenerResp, err := d.sdkClient.UpdateListenerAttribute(updateListenerAttributeReq)
	d.logger.Debug("sdk request 'ulb.UpdateListenerAttribute'", slog.Any("request", updateListenerAttributeReq), slog.Any("response", updateListenerResp))
	if err != nil {
		return fmt.Errorf("failed to execute sdk request 'ulb.UpdateListenerAttribute': %w", err)
	}

	return nil
}

func (d *Deployer) updateListenerSniCertificate(ctx context.Context, cloudLoadbalancerId string, cloudListenerInfo ulb.Listener, cloudCertId string) error {
	// 新增监听器扩展证书
	// REF: https://docs.ucloud.cn/api/ulb-api/add_ssl_binding_json
	addSSLBindingReq := d.sdkClient.NewAddSSLBindingRequest()
	addSSLBindingReq.LoadBalancerId = ucloud.String(cloudLoadbalancerId)
	addSSLBindingReq.ListenerId = ucloud.String(cloudListenerInfo.ListenerId)
	addSSLBindingReq.SSLIds = []string{cloudCertId}
	addSSLBindingResp, err := d.sdkClient.AddSSLBinding(addSSLBindingReq)
	d.logger.Debug("sdk request 'ulb.AddSSLBinding'", slog.Any("request", addSSLBindingReq), slog.Any("response", addSSLBindingResp))
	if err != nil {
		return fmt.Errorf("failed to execute sdk request 'ulb.AddSSLBinding': %w", err)
	}

	// 找出需要删除绑定的扩展证书
	// REF: https://docs.ucloud.cn/api/ulb-api/describe_sslv2
	sslIdsToDelete := make([]string, 0)
	for _, certItem := range cloudListenerInfo.Certificates {
		if certItem.IsDefault {
			continue
		}

		describeSSLV2Req := d.sdkClient.NewDescribeSSLV2Request()
		describeSSLV2Req.SSLId = ucloud.String(certItem.SSLId)
		describeSSLV2Req.Limit = ucloud.Int(1)
		describeSSLV2Resp, err := d.sdkClient.DescribeSSLV2(describeSSLV2Req)
		d.logger.Debug("sdk request 'ulb.DescribeSSLV2'", slog.Any("request", describeSSLV2Req), slog.Any("response", describeSSLV2Resp))
		if err != nil {
			continue
		} else if len(describeSSLV2Resp.DataSet) == 0 {
			continue
		}

		sslItem := describeSSLV2Resp.DataSet[0]
		if sslItem.Domains == d.config.Domain {
			sslIdsToDelete = append(sslIdsToDelete, sslItem.SSLId) // 同域名证书需要删除
			continue
		} else if sslItem.NotAfter != 0 && int64(sslItem.NotAfter) < time.Now().Unix() {
			sslIdsToDelete = append(sslIdsToDelete, sslItem.SSLId) // 过期证书需要删除。TODO: remove on v0.5
			continue
		}
	}

	// 删除监听器绑定的扩展证书
	// REF: https://docs.ucloud.cn/api/ulb-api/delete_ssl_binding_json
	if len(sslIdsToDelete) > 0 {
		d.logger.Info("found alb listener certificates to unbind", slog.Any("sslIds", sslIdsToDelete))

		deleteSSLBindingReq := d.sdkClient.NewDeleteSSLBindingRequest()
		deleteSSLBindingReq.LoadBalancerId = ucloud.String(cloudLoadbalancerId)
		deleteSSLBindingReq.ListenerId = ucloud.String(cloudListenerInfo.ListenerId)
		deleteSSLBindingReq.SSLIds = sslIdsToDelete
		deleteSSLBindingResp, err := d.sdkClient.DeleteSSLBinding(deleteSSLBindingReq)
		d.logger.Debug("sdk request 'ulb.DeleteSSLBinding'", slog.Any("request", deleteSSLBindingReq), slog.Any("response", deleteSSLBindingResp))
		if err != nil {
			return fmt.Errorf("failed to execute sdk request 'ulb.DeleteSSLBinding': %w", err)
		}
	}

	return nil
}

func createSDKClient(privateKey, publicKey, projectId, region string) (*ucloudsdk.ULBClient, error) {
	if privateKey == "" {
		return nil, fmt.Errorf("ucloud: invalid private key")
	}
	if publicKey == "" {
		return nil, fmt.Errorf("ucloud: invalid public key")
	}

	cfg := ucloud.NewConfig()
	cfg.ProjectId = projectId
	cfg.Region = region

	credential := auth.NewCredential()
	credential.PrivateKey = privateKey
	credential.PublicKey = publicKey

	client := ucloudsdk.NewClient(&cfg, &credential)
	return client, nil
}
