package manager

import "fmt"

// CopySecretInput represents the input of a CopySecret operation
type CopySecretInput struct {
	Source      string
	Destination string
	ActionUser  string
}

// CopySecretOutput represents the output of a CopySecret operation
type CopySecretOutput struct{}

func (input *CopySecretInput) validate() (err error) {
	if input.Source == "" {
		err = &InputValidationError{"invalid input, source is required field"}
	} else if input.Destination == "" {
		err = &InputValidationError{"invalid input, destination is required field"}
	}
	return
}

// Copy will copy a secret from name source to name destination inside
// the same table. The user will need to able to read and decrypt the
// old secret along with encrypting and writing the new secret.
func (m *Manager) Copy(source, destination string) (err error) {
	input := &CopySecretInput{
		Source:      source,
		Destination: destination,
		ActionUser:  m.Config.ActionUser,
	}

	_, err = m.CopySecret(input)
	return
}

// CopySecret Copy will copy a secret from name source to name destination
// inside the same table. The user will need to able to read and decrypt the
// old secret along with encrypting and writing the new secret.
func (m *Manager) CopySecret(input *CopySecretInput) (output *CopySecretOutput, err error) {

	err = input.validate()
	if err != nil {
		return
	}

	secret, err := m.Get(input.Source)
	if err != nil {
		return
	}
	if secret == nil {
		err = fmt.Errorf("source secret '%s' not found", input.Source)
		return
	}

	secret.Name = input.Destination
	if input.ActionUser != "" {
		secret.ActionUser = input.ActionUser
	}
	// copy needs to zero out cross_env
	secret.CrossEnv = false
	err = m.Post(secret)
	return
}
