package packspec

import (
	"bytes"
	"encoding/json"
	"strings"
)

// CoerceSpecDefault maps a raw JSON "default" value from the spec to the
// string form stored in _System_Field.DefaultValue, plus an "is set" flag.
//
//   - missing / JSON null / empty string → ("", false)   — no default
//   - JSON string  "Draft"   → ("Draft", true)
//   - JSON string  ""        → ("", false)               — treated as absent
//   - JSON number  0         → ("0", true)
//   - JSON boolean false     → ("false", true)
//   - any other scalar       → (raw text, true)          — never panics
//
// Shared by reconcileStandardFieldDefaultValues (apply) and
// VerifyStandardFieldSpecDrift (verify) so both paths agree on what counts
// as "the spec has a default" and what string it materializes to.
func CoerceSpecDefault(raw json.RawMessage) (string, bool) {
	if len(raw) == 0 {
		return "", false
	}
	if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
		return "", false
	}
	if raw[0] == '"' {
		var s string
		if err := json.Unmarshal(raw, &s); err != nil {
			return "", false
		}
		if s == "" {
			return "", false
		}
		return s, true
	}
	return strings.TrimSpace(string(raw)), true
}
