// Copyright 2023 Woodpecker Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package base

import (
	"errors"
	"fmt"
)

// StringOrSlice represents a string or an array of strings.
// We need to override the yaml decoder to accept both options.
type StringOrSlice []string

// UnmarshalYAML implements the Unmarshaler interface.
func (s *StringOrSlice) UnmarshalYAML(unmarshal func(any) error) error {
	var stringType string
	if err := unmarshal(&stringType); err == nil {
		*s = []string{stringType}
		return nil
	}

	var sliceType []any
	if err := unmarshal(&sliceType); err == nil {
		parts, err := toStrings(sliceType)
		if err != nil {
			return err
		}
		*s = parts
		return nil
	}

	return errors.New("failed to unmarshal StringOrSlice")
}

// MarshalYAML implements custom Yaml marshaling.
func (s StringOrSlice) MarshalYAML() (any, error) {
	if len(s) == 0 {
		return nil, nil
	} else if len(s) == 1 {
		return s[0], nil
	}
	return []string(s), nil
}

func toStrings(s []any) ([]string, error) {
	if s == nil {
		return nil, nil
	}
	r := make([]string, len(s))
	for k, v := range s {
		if sv, ok := v.(string); ok {
			r[k] = sv
		} else {
			return nil, fmt.Errorf("cannot unmarshal '%v' of type %T into a string value", v, v)
		}
	}
	return r, nil
}
