package ghpkg

import (
	"fmt"
	"strings"
)

type ResourcePoolItem struct {
	Path         string `yaml:"path,omitempty"`
	ResourcePool string `yaml:"resourcePool,omitempty"`
	Action       string `yaml:"action,omitempty"`
}

func GetResourcePool(pools []ResourcePoolItem, planPath string, currentPool string) (string, error) {
	result := currentPool
	for _, pool := range pools {
		if !IsResourcePoolMatch(pool.Path, planPath) {
			continue
		}
		switch {
		case pool.ResourcePool != "":
			result = pool.ResourcePool
		case pool.Action == "KEEP":
			result = currentPool
		default:
			return "", fmt.Errorf("unknown action for path '%s': %s", pool.Path, pool.Action)
		}
	}
	return result, nil
}

func IsResourcePoolMatch(path string, planPath string) bool {
	if path == "*" || path == "" {
		return true
	}
	return strings.HasPrefix(planPath, path)
}
