package ci

import "gopkg.in/yaml.v3"

// WorkflowFile is the parsed representation of a .forgebucket/workflows/*.yml file.
type WorkflowFile struct {
	Name string                 `yaml:"name"`
	On   WorkflowTrigger        `yaml:"on"`
	Jobs map[string]WorkflowJob `yaml:"jobs"`
}

type WorkflowTrigger struct {
	Push        *PushTrigger `yaml:"push"`
	PullRequest *PRTrigger   `yaml:"pull_request"`
}

type PushTrigger struct {
	Branches []string `yaml:"branches"`
	Tags     []string `yaml:"tags"`
}

type PRTrigger struct {
	Branches []string `yaml:"branches"`
}

type WorkflowJob struct {
	Name   string         `yaml:"name"`
	RunsOn string         `yaml:"runs-on"`
	Needs  StringOrSlice  `yaml:"needs"`
	Steps  []WorkflowStep `yaml:"steps"`
}

type WorkflowStep struct {
	Name string            `yaml:"name"`
	Uses string            `yaml:"uses"`
	Run  string            `yaml:"run"`
	Env  map[string]string `yaml:"env"`
}

// StringOrSlice unmarshals a YAML value that may be either a single string
// ("needs: test") or a list ("needs: [test, build]").
type StringOrSlice []string

func (s *StringOrSlice) UnmarshalYAML(value *yaml.Node) error {
	switch value.Kind {
	case yaml.ScalarNode:
		if value.Value != "" {
			*s = []string{value.Value}
		}
	case yaml.SequenceNode:
		var items []string
		if err := value.Decode(&items); err != nil {
			return err
		}
		*s = items
	}
	return nil
}
