package plan

import "sort"

type Severity string

const (
	SeverityError   Severity = "error"
	SeverityWarning Severity = "warning"
)

// Diagnostic is stable enough to be persisted and mapped back to either the
// YAML editor or graph editor. Code is machine-readable; Message is not.
type Diagnostic struct {
	Severity Severity `json:"severity"`
	Code     string   `json:"code"`
	Path     string   `json:"path"`
	Message  string   `json:"message"`
	Line     int      `json:"line,omitempty"`
	Column   int      `json:"column,omitempty"`
	NodeID   string   `json:"nodeId,omitempty"`
	EdgeID   string   `json:"edgeId,omitempty"`
}

func HasErrors(diagnostics []Diagnostic) bool {
	for _, diagnostic := range diagnostics {
		if diagnostic.Severity == SeverityError {
			return true
		}
	}
	return false
}

func sortDiagnostics(diagnostics []Diagnostic) {
	sort.SliceStable(diagnostics, func(i, j int) bool {
		a, b := diagnostics[i], diagnostics[j]
		if a.Line != b.Line {
			if a.Line == 0 {
				return false
			}
			if b.Line == 0 {
				return true
			}
			return a.Line < b.Line
		}
		if a.Column != b.Column {
			return a.Column < b.Column
		}
		if a.Path != b.Path {
			return a.Path < b.Path
		}
		return a.Code < b.Code
	})
}
