package resume

import (
	"haixun-backend/internal/model/job/domain/entity"
	"haixun-backend/internal/model/job/domain/enum"
)

func ShouldSkipStep(status enum.StepStatus) bool {
	return status == enum.StepStatusSucceeded
}

func StepProgressByID(steps []entity.StepProgress, stepID string) *entity.StepProgress {
	for i := range steps {
		if steps[i].ID == stepID {
			return &steps[i]
		}
	}
	return nil
}

func PrepareStepsForRetry(steps []entity.StepProgress) []entity.StepProgress {
	out := make([]entity.StepProgress, len(steps))
	for i, step := range steps {
		out[i] = step
		if step.Status == enum.StepStatusSucceeded {
			continue
		}
		out[i].Status = enum.StepStatusPending
		out[i].StartedAt = nil
		out[i].EndedAt = nil
		out[i].Message = ""
	}
	return out
}

func FirstResumablePhase(steps []entity.StepProgress) string {
	for _, step := range steps {
		if step.Status != enum.StepStatusSucceeded {
			return step.ID
		}
	}
	if len(steps) == 0 {
		return ""
	}
	return steps[len(steps)-1].ID
}

func CalcProgressPercentage(steps []entity.StepProgress) int {
	if len(steps) == 0 {
		return 0
	}
	done := 0
	for _, step := range steps {
		if step.Status == enum.StepStatusSucceeded {
			done++
		}
	}
	return (done * 100) / len(steps)
}

func CountSucceededSteps(steps []entity.StepProgress) int {
	count := 0
	for _, step := range steps {
		if step.Status == enum.StepStatusSucceeded {
			count++
		}
	}
	return count
}
