package baiducloudblb

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

	bceblb "github.com/baidubce/bce-sdk-go/services/blb"
	"github.com/pocketbase/pocketbase/tools/security"
	"github.com/samber/lo"

	"github.com/certimate-go/certimate/pkg/core"
	cmgrimpl "github.com/certimate-go/certimate/pkg/core/certmgr/providers/baiducloud-cert"
	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"`
	// 百度智能云区域。
	Region string `json:"region"`
	// 部署目标。
	DeployTarget string `json:"deployTarget"`
	// 负载均衡实例 ID。
	// 部署目标为 [DEPLOY_TARGET_LOADBALANCER]、[DEPLOY_TARGET_LISTENER] 时必填。
	LoadbalancerId string `json:"loadbalancerId,omitempty"`
	// 负载均衡监听端口。
	// 部署目标为 [DEPLOY_TARGET_LISTENER] 时必填。
	ListenerPort int32 `json:"listenerPort,omitempty"`
	// SNI 域名（支持泛域名）。
	// 部署目标为 [DEPLOY_TARGET_LOADBALANCER]、[DEPLOY_TARGET_LISTENER] 时选填。
	Domain string `json:"domain,omitempty"`
}

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

	pcertmgr, err := cmgrimpl.NewCertmgr(&cmgrimpl.CertmgrConfig{
		AccessKeyId:     config.AccessKeyId,
		SecretAccessKey: config.SecretAccessKey,
	})
	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")
	}

	// 查询 BLB 实例详情
	// REF: https://cloud.baidu.com/doc/BLB/s/njwvxnv79#describeloadbalancerdetail%E6%9F%A5%E8%AF%A2blb%E5%AE%9E%E4%BE%8B%E8%AF%A6%E6%83%85
	describeLoadBalancerDetailResp, err := d.sdkClient.DescribeLoadBalancerDetail(d.config.LoadbalancerId)
	d.logger.Debug("sdk request 'blb.DescribeLoadBalancerAttribute'", slog.String("params.blbId", d.config.LoadbalancerId), slog.Any("response", describeLoadBalancerDetailResp))
	if err != nil {
		return fmt.Errorf("failed to execute sdk request 'blb.DescribeLoadBalancerDetail': %w", err)
	}

	// 获取全部 HTTPS/SSL 监听端口
	type listenerEntry struct {
		Type string
		Port int32
	}
	listeners := make([]listenerEntry, 0)
	for _, listener := range describeLoadBalancerDetailResp.Listener {
		if listener.Type == "HTTPS" || listener.Type == "SSL" {
			listenerPort, err := strconv.Atoi(listener.Port)
			if err != nil {
				continue
			}

			listeners = append(listeners, listenerEntry{
				Type: listener.Type,
				Port: int32(listenerPort),
			})
		}
	}

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

		if err := xloop.ForRangeAllWithContext(ctx, listeners, func(ctx context.Context, listener listenerEntry, _ int) error {
			return d.updateListenerCertificate(ctx, d.config.LoadbalancerId, listener.Type, listener.Port, 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.ListenerPort == 0 {
		return fmt.Errorf("config `listenerPort` is required")
	}

	// 查询监听
	// REF: https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#describealllisteners%E6%9F%A5%E8%AF%A2%E6%89%80%E6%9C%89%E7%9B%91%E5%90%AC
	describeAllListenersRequest := &bceblb.DescribeListenerArgs{
		ListenerPort: uint16(d.config.ListenerPort),
	}
	describeAllListenersResp, err := d.sdkClient.DescribeAllListeners(d.config.LoadbalancerId, describeAllListenersRequest)
	d.logger.Debug("sdk request 'blb.DescribeAllListeners'", slog.String("params.blbId", d.config.LoadbalancerId), slog.Any("request", describeAllListenersRequest), slog.Any("response", describeAllListenersResp))
	if err != nil {
		return fmt.Errorf("failed to execute sdk request 'blb.DescribeAllListeners': %w", err)
	}

	// 获取全部 HTTPS/SSL 监听端口
	type listenerEntry struct {
		Type string
		Port int32
	}
	listeners := make([]listenerEntry, 0)
	for _, listener := range describeAllListenersResp.AllListenerList {
		if listener.ListenerType == "HTTPS" || listener.ListenerType == "SSL" {
			listeners = append(listeners, listenerEntry{
				Type: listener.ListenerType,
				Port: int32(listener.ListenerPort),
			})
		}
	}

	// 更新监听证书
	if err := xloop.ForRangeAllWithContext(ctx, listeners, func(ctx context.Context, listener listenerEntry, _ int) error {
		return d.updateListenerCertificate(ctx, d.config.LoadbalancerId, listener.Type, listener.Port, cloudCertId)
	}); err != nil {
		return err
	}

	return nil
}

func (d *Deployer) updateListenerCertificate(ctx context.Context, cloudLoadbalancerId string, cloudListenerType string, cloudListenerPort int32, cloudCertId string) error {
	switch strings.ToUpper(cloudListenerType) {
	case "HTTPS":
		return d.updateHttpsListenerCertificate(ctx, cloudLoadbalancerId, cloudListenerPort, cloudCertId)
	case "SSL":
		return d.updateSslListenerCertificate(ctx, cloudLoadbalancerId, cloudListenerPort, cloudCertId)
	default:
		return fmt.Errorf("unsupported listener type '%s'", cloudListenerType)
	}
}

func (d *Deployer) updateHttpsListenerCertificate(ctx context.Context, cloudLoadbalancerId string, cloudHttpsListenerPort int32, cloudCertId string) error {
	// 查询 HTTPS 监听器
	// REF: https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#describehttpslisteners%E6%9F%A5%E8%AF%A2https%E7%9B%91%E5%90%AC%E5%99%A8
	describeHTTPSListenersReq := &bceblb.DescribeListenerArgs{
		ListenerPort: uint16(cloudHttpsListenerPort),
		MaxKeys:      1,
	}
	describeHTTPSListenersResp, err := d.sdkClient.DescribeHTTPSListeners(cloudLoadbalancerId, describeHTTPSListenersReq)
	d.logger.Debug("sdk request 'blb.DescribeHTTPSListeners'", slog.String("params.blbId", cloudLoadbalancerId), slog.Any("request", describeHTTPSListenersReq), slog.Any("response", describeHTTPSListenersResp))
	if err != nil {
		return fmt.Errorf("failed to execute sdk request 'blb.DescribeHTTPSListeners': %w", err)
	} else if len(describeHTTPSListenersResp.ListenerList) == 0 {
		return fmt.Errorf("could not find blb listener '%s:%d'", cloudLoadbalancerId, cloudHttpsListenerPort)
	}

	listenerInfo := describeHTTPSListenersResp.ListenerList[0]
	if d.config.Domain == "" {
		// 未指定 SNI，只需部署到监听器
		if lo.SomeBy(listenerInfo.CertIds, func(item string) bool { return item == cloudCertId }) {
			d.logger.Info("no need to deploy blb listener default certificate")
			return nil
		}
		return d.updateHttpsListenerDefaultCertificate(ctx, cloudLoadbalancerId, &listenerInfo, cloudCertId)
	} else {
		// 指定 SNI，需部署到扩展域名
		return d.updateHttpsListenerSniCertificate(ctx, cloudLoadbalancerId, &listenerInfo, cloudCertId)
	}
}

func (d *Deployer) updateHttpsListenerDefaultCertificate(ctx context.Context, cloudLoadbalancerId string, cloudHttpsListenerInfo *bceblb.HTTPSListenerModel, cloudCertId string) error {
	// 更新 HTTPS 监听器
	// REF: https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#updatehttpslistener%E6%9B%B4%E6%96%B0https%E7%9B%91%E5%90%AC%E5%99%A8
	updateHTTPSListenerReq := &bceblb.UpdateHTTPSListenerArgs{
		ClientToken:  security.RandomString(32),
		ListenerPort: cloudHttpsListenerInfo.ListenerPort,
		CertIds:      []string{cloudCertId},
	}
	err := d.sdkClient.UpdateHTTPSListener(cloudLoadbalancerId, updateHTTPSListenerReq)
	d.logger.Debug("sdk request 'blb.UpdateHTTPSListener'", slog.Any("request", updateHTTPSListenerReq))
	if err != nil {
		return fmt.Errorf("failed to execute sdk request 'blb.UpdateHTTPSListener': %w", err)
	}

	return nil
}

func (d *Deployer) updateHttpsListenerSniCertificate(ctx context.Context, cloudLoadbalancerId string, cloudHttpsListenerInfo *bceblb.HTTPSListenerModel, cloudCertId string) error {
	// 更新 HTTPS 监听器
	// REF: https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#updatehttpslistener%E6%9B%B4%E6%96%B0https%E7%9B%91%E5%90%AC%E5%99%A8
	updateHTTPSListenerReq := &bceblb.UpdateHTTPSListenerArgs{
		ClientToken:  security.RandomString(32),
		ListenerPort: cloudHttpsListenerInfo.ListenerPort,
		CertIds:      cloudHttpsListenerInfo.CertIds,
		AdditionalCertDomains: lo.Map(cloudHttpsListenerInfo.AdditionalCertDomains, func(domain bceblb.AdditionalCertDomainsModel, _ int) bceblb.AdditionalCertDomainsModel {
			if domain.Host == d.config.Domain {
				return bceblb.AdditionalCertDomainsModel{
					Host:   domain.Host,
					CertId: cloudCertId,
				}
			}

			return bceblb.AdditionalCertDomainsModel{
				Host:   domain.Host,
				CertId: domain.CertId,
			}
		}),
	}
	err := d.sdkClient.UpdateHTTPSListener(cloudLoadbalancerId, updateHTTPSListenerReq)
	d.logger.Debug("sdk request 'blb.UpdateHTTPSListener'", slog.Any("request", updateHTTPSListenerReq))
	if err != nil {
		return fmt.Errorf("failed to execute sdk request 'blb.UpdateHTTPSListener': %w", err)
	}

	return nil
}

func (d *Deployer) updateSslListenerCertificate(ctx context.Context, cloudLoadbalancerId string, cloudHttpsListenerPort int32, cloudCertId string) error {
	// 更新 SSL 监听器
	// REF: https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#updatessllistener%E6%9B%B4%E6%96%B0ssl%E7%9B%91%E5%90%AC%E5%99%A8
	updateSSLListenerReq := &bceblb.UpdateSSLListenerArgs{
		ClientToken:  security.RandomString(32),
		ListenerPort: uint16(cloudHttpsListenerPort),
		CertIds:      []string{cloudCertId},
	}
	err := d.sdkClient.UpdateSSLListener(cloudLoadbalancerId, updateSSLListenerReq)
	d.logger.Debug("sdk request 'blb.UpdateSSLListener'", slog.Any("request", updateSSLListenerReq))
	if err != nil {
		return fmt.Errorf("failed to execute sdk request 'blb.UpdateSSLListener': %w", err)
	}

	return nil
}

func createSDKClient(accessKeyId, secretAccessKey, region string) (*bceblb.Client, error) {
	endpoint := ""
	if region != "" {
		endpoint = fmt.Sprintf("blb.%s.baidubce.com", region)
	}

	client, err := bceblb.NewClient(accessKeyId, secretAccessKey, endpoint)
	if err != nil {
		return nil, err
	}

	return client, nil
}
