package br

import (
	"context"
	"strconv"

	"google.golang.org/protobuf/proto"

	globalcommonv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/common/v1"
	globalngv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/nextgen/v1"
	"github.com/tidbcloud/tidb-management-service/nextgen-global-service/infra/repoimpl/schema"
	"github.com/tidbcloud/tidb-management-service/utilities/bizerr"
)

// BackfillEssentialV2BackupSetting converts a standard-bundle Essential V2
// setting to 30-day flexible retention. The fresh read and versioned save make
// the operation conditional: a concurrent user update is never overwritten.
func (s *serviceImpl) BackfillEssentialV2BackupSetting(
	ctx context.Context,
	clusterID uint64,
) (bool, bizerr.BizError) {
	backupSettingInDB, berr := s.backupSettingRepo.Get(ctx, clusterID)
	if berr != nil {
		return false, berr.Chain("failed to get backup setting from db")
	}
	if backupSettingInDB.ServicePlan != globalcommonv1.ServicePlan_Essential_V2.String() {
		return false, bizerr.New(bizerr.ErrCodeParams, "cluster %d is not an essential_v2 cluster", clusterID)
	}
	if backupSettingInDB.Mode != schema.BackupModeStandardBundle {
		return false, nil
	}

	_, berr = s.updateBackupSettingWithEntity(
		ctx,
		newEssentialV2BackfillRequest(clusterID),
		backupSettingInDB,
		backupSettingUpdateSourceSystemBackfill,
	)
	if berr != nil {
		return false, berr
	}
	return true, nil
}

func newEssentialV2BackfillRequest(clusterID uint64) *globalngv1.UpdateBackupSettingRequest {
	return &globalngv1.UpdateBackupSettingRequest{
		BackupSetting: &globalngv1.BackupSetting{
			ClusterId:          strconv.FormatUint(clusterID, 10),
			Mode:               globalngv1.BackupSetting_FLEXIBLE_RETENTION,
			RetentionDays:      proto.Int32(EssentialV2BackfillRetentionDays),
			DailyBackupTimeUtc: proto.String(DefaultDailyBackupTimeUTC),
		},
	}
}
