// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package actions

import (
	"slices"

	actions_model "forgejo.org/models/actions"
	"forgejo.org/modules/container"
)

// GetAllRerunJobs get all jobs that need to be rerun when job should be rerun
func GetAllRerunJobs(job *actions_model.ActionRunJob, allJobs []*actions_model.ActionRunJob) []*actions_model.ActionRunJob {
	rerunJobs := []*actions_model.ActionRunJob{job}
	rerunJobsIDSet := make(container.Set[string])
	rerunJobsIDSet.Add(job.JobID)

	for {
		found := false
		for _, j := range allJobs {
			if rerunJobsIDSet.Contains(j.JobID) {
				continue
			}
			if slices.ContainsFunc(j.Needs, rerunJobsIDSet.Contains) {
				found = true
				rerunJobs = append(rerunJobs, j)
				rerunJobsIDSet.Add(j.JobID)
			}
		}
		if !found {
			break
		}
	}

	return rerunJobs
}
