package handler

import (
	"encoding/json"
	"net/http"

	"codeberg.org/VARASYS/ZDDC/zddc/internal/policy"
)

// writeForbidden emits a 403 JSON response naming the missing verb. Used
// at every ACL-deny site so the client-side toast can render a specific
// "you need <verb> here" message and offer elevation when the path-scoped
// /.profile/access?path= reports a would_elevate_grant covering that verb.
//
// Body shape:
//
//	{"error": "Forbidden", "missing_verb": "w"}
//
// Existing clients that read the body as text see the JSON string instead
// of "Forbidden\n" — both are diagnostic-only display strings, no client
// in this repo parses the previous plain-text body for content. Used in
// place of `http.Error(w, "Forbidden", http.StatusForbidden)` exclusively
// for ACL-deny cases. Other 403 conditions (no authenticated principal,
// existence-leak guards, etc.) keep the plain-text variant since
// "missing_verb" doesn't apply to them.
func writeForbidden(w http.ResponseWriter, action string) {
	verb := verbForAction(action)
	body, _ := json.Marshal(map[string]string{
		"error":        "Forbidden",
		"missing_verb": verb,
	})
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(http.StatusForbidden)
	_, _ = w.Write(body)
}

// verbForAction maps a policy.Action constant to its single-character
// verb. Mirrors policy.actionVerb but emits the wire-format letter
// rather than the bitmask, so the JSON body carries "r"/"w"/"c"/"d"/"a"
// — the same alphabet the listing's `verbs` field uses.
func verbForAction(action string) string {
	switch action {
	case policy.ActionWrite:
		return "w"
	case policy.ActionCreate:
		return "c"
	case policy.ActionDelete:
		return "d"
	case policy.ActionAdmin:
		return "a"
	default:
		return "r"
	}
}
