package artifacts

import (
	"context"
	"fmt"

	"github.com/databricks/cli/bundle"
	"github.com/databricks/cli/libs/diag"
)

func BuildAll() bundle.Mutator {
	return &all{
		name: "Build",
		fn:   buildArtifactByName,
	}
}

type build struct {
	name string
}

func buildArtifactByName(name string) (bundle.Mutator, error) {
	return &build{name}, nil
}

func (m *build) Name() string {
	return fmt.Sprintf("artifacts.Build(%s)", m.name)
}

func (m *build) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostics {
	artifact, ok := b.Config.Artifacts[m.name]
	if !ok {
		return diag.Errorf("artifact doesn't exist: %s", m.name)
	}

	var mutators []bundle.Mutator

	// Skip building if build command is not specified or infered
	if artifact.BuildCommand == "" {
		// If no build command was specified or infered and there is no
		// artifact output files specified, artifact is misconfigured
		if len(artifact.Files) == 0 {
			return diag.Errorf("misconfigured artifact: please specify 'build' or 'files' property")
		}

		// We can skip calling build mutator if there is no build command
		// But we still need to expand glob references in files source path.
	} else {
		mutators = append(mutators, getBuildMutator(artifact.Type, m.name))
	}

	// We need to expand glob reference after build mutator is applied because
	// if we do it before, any files that are generated by build command will
	// not be included into artifact.Files and thus will not be uploaded.
	mutators = append(mutators, &expandGlobs{name: m.name})
	return bundle.Apply(ctx, b, bundle.Seq(mutators...))
}