package tfmigrate

import (
	"context"

	"github.com/minamijoyo/tfmigrate/tfexec"
)

// StateReplaceProviderAction implements the StateAction interface.
// StateReplaceProviderAction replaces a provider from source address to destination address in
// the same tfstate file.
type StateReplaceProviderAction struct {
	// source is the provider address to be replaced.
	source string
	// destination is the new provider address.
	destination string
}

var _ StateAction = (*StateReplaceProviderAction)(nil)

// NewStateReplaceProviderAction returns a new StateReplaceProviderAction instance.
func NewStateReplaceProviderAction(source string, destination string) *StateReplaceProviderAction {
	return &StateReplaceProviderAction{
		source:      source,
		destination: destination,
	}
}

// StateUpdate updates a given state and returns a new state.
// It moves a provider from source address to destination address in the same tfstate file.
func (a *StateReplaceProviderAction) StateUpdate(ctx context.Context, tf tfexec.TerraformCLI, state *tfexec.State) (*tfexec.State, error) {
	// Disable unnecessary state backup here,
	// because we never restore state from the backup generated by each state action.
	// The state replace-provider command doesn't provide a way to disable it, so we backup to /dev/null.
	return tf.StateReplaceProvider(ctx, state, a.source, a.destination, "-backup=/dev/null", "-auto-approve")
}
