package br

import (
	"fmt"

	"github.com/tidbcloud/cluster-service-ng/pkg/runtime/actions"
	"github.com/tidbcloud/cluster-service-ng/pkg/storage/mysql/schema"
	"github.com/tidbcloud/cluster-service-ng/pkg/storage/repo"
	"github.com/tidbcloud/cluster-service-ng/pkg/utils"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
)

const MarkManualBackupDeletingActionName = "mark-manual-backup-deleting"

type markManualBackupDeletingAction struct {
	manualBackupRepo repo.ManualBackupRepo
}

func NewMarkManualBackupDeletingAction(manualBackupRepo repo.ManualBackupRepo) actions.Action {
	return &markManualBackupDeletingAction{manualBackupRepo: manualBackupRepo}
}

func (a *markManualBackupDeletingAction) Name() string {
	return MarkManualBackupDeletingActionName
}

func (a *markManualBackupDeletingAction) Invoke(args actions.ActionArgs) error {
	ctx := utils.GenerateContext(args)
	backupID, ok := GetManualBackupID(args)
	if !ok {
		return fmt.Errorf("manual backup id is not found")
	}

	clusterID, ok := GetTiDBClusterID(args)
	if !ok {
		return fmt.Errorf("tidb cluster id is not found")
	}

	manualBackup, err := a.manualBackupRepo.Load(ctx, clusterID, backupID, true)
	if err != nil {
		tilog.Error(ctx, "failed to load manual backup", zap.Error(err), zap.String("backupId", backupID), zap.String("clusterId", clusterID))
		return fmt.Errorf("failed to load manual backup: %w", err)
	}

	err = AddActionForManualBackup(ctx, a.manualBackupRepo, manualBackup, schema.ManualBackupActionMarkDeleted)
	if err != nil {
		tilog.Error(ctx, "failed to add action to manual backup", zap.Error(err), zap.String("backupId", backupID), zap.String("clusterId", clusterID))
		return fmt.Errorf("failed to add action to manual backup: %w", err)
	}

	err = a.manualBackupRepo.SetStatus(ctx, clusterID, backupID, schema.ManualBackupStatusDeleting)
	if err != nil {
		tilog.Error(ctx, "failed to set manual backup status", zap.Error(err), zap.String("backupId", backupID), zap.String("clusterId", clusterID))
		return fmt.Errorf("failed to set manual backup status: %w", err)
	}

	return nil
}
