package server

import (
	"context"
	"fmt"

	"github.com/elliotchance/pie/v2"
	apiv1 "github.com/tidbcloud/cluster-service-ng/api/cluster-service-ng/v1beta"
	"github.com/tidbcloud/cluster-service-ng/pkg/clustergateway"
	"github.com/tidbcloud/cluster-service-ng/pkg/tioperator"
	"github.com/tidbcloud/cluster-service-ng/pkg/utils"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
)

type ListLightweightBackupsInput struct {
	*apiv1.ListLightweightBackupsRequest
}

type ListLightweightBackupsOutput struct {
	ListLightweightBackupsResponse clustergateway.ListLightweightBackupsResponse
	DfsPrefix                      string
	DfsBucket                      string
	DfsRegion                      string
	Keyspace2ClusterId             map[string]string
}

func (s *serverImpl) ListLightweightBackups(ctx context.Context, upReq *ListLightweightBackupsInput) (*ListLightweightBackupsOutput, error) {
	sharedPool, err := s.sharedPoolRepo.Load(ctx, upReq.SharedPoolId, false)
	if err != nil {
		return nil, fmt.Errorf("query sharedPool failed: %w", err)
	}
	downReq := &clustergateway.ListLightweightBackupsRequest{
		FromPrefix:  upReq.FromPrefix,
		LoadDetails: upReq.LoadDetails,
		MaxCount:    upReq.MaxCount,
	}
	resp, err := s.clustergatewayCli.ListLightweightBackups(ctx, sharedPool, tioperator.DefaultTiBRName, downReq)
	if err != nil {
		tilog.Error(ctx, "proxy ListLightweightBackups failed",
			zap.Error(err), zap.String("request", utils.JSON(downReq)), zap.String("sharedPool", sharedPool.Id))
		return nil, fmt.Errorf("proxy call failed: %w", err)
	}
	tilog.Info(ctx, "proxy ListLightweightBackups succeeded", zap.String("request", utils.JSON(downReq)),
		zap.String("sharedPool", sharedPool.String()), zap.String("response", utils.JSON(resp)))

	kespaces := map[string]bool{}
	for _, it := range resp.Data {
		for _, k := range it.Details.Keyspaces {
			if !k.IsNormalKeyspace() {
				continue
			}
			kespaces[k.KeyspaceName] = true
		}
	}
	k2c, err := s.keyspaceFetcher.GetClusterIds(ctx, upReq.SharedPoolId, pie.Sort(pie.Keys(kespaces)))
	if err != nil {
		tilog.Error(ctx, "GetClusterIds failed",
			zap.Error(err), zap.String("request", utils.JSON(downReq)), zap.String("sharedPool", sharedPool.Id))
		return nil, fmt.Errorf("GetClusterIds failed: %w", err)
	}

	return &ListLightweightBackupsOutput{
		ListLightweightBackupsResponse: *resp,
		DfsPrefix:                      sharedPool.GetDfsPrefix(),
		DfsBucket:                      sharedPool.GetObjectStorage().GetBucket(),
		DfsRegion:                      sharedPool.GetObjectStorage().GetRegion(),
		Keyspace2ClusterId:             k2c,
	}, nil
}
