package utils

import (
	"context"
	"slices"
	"strings"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/route53"
	"github.com/aws/aws-sdk-go-v2/service/route53/types"
	"github.com/juju/errors"
	"github.com/tidbcloud/auto-deploy/internal/constants"
)

func GetHostZoneId(hostedZoneName string) (string, error) {
	if !strings.HasSuffix(hostedZoneName, ".") {
		hostedZoneName = hostedZoneName + "."
	}

	ctx := context.Background()
	cfg, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		return "", errors.Annotatef(err, "Failed to load default aws config")
	}

	client := route53.NewFromConfig(cfg)
	result, err := client.ListHostedZonesByName(ctx, &route53.ListHostedZonesByNameInput{
		DNSName: &hostedZoneName,
	})
	if err != nil {
		return "", errors.Annotatef(err, "Failed to list hosted zones: %s", hostedZoneName)
	}

	index := slices.IndexFunc(result.HostedZones, func(z types.HostedZone) bool {
		return *z.Name == hostedZoneName
	})
	if index < 0 {
		return "", errors.Annotatef(err, "Failed to find hosted zone %s, please check if the hosted zone is created on AWS web console.", hostedZoneName)
	}

	hostedZoneId := strings.TrimPrefix(*result.HostedZones[index].Id, constants.AWS_HOSTED_ZONE_ID_PREFIX)
	return hostedZoneId, nil
}
