package authorization

import "fmt"

const fmtErrExpectedKey = "expected authorization context key '%s'"
const fmtErrUnexpectedKey = "unexpected authorization context key '%s'"

type Context map[string]string

func ValidateContext(c Context) error {
	if !c.HasEventType() {
		return fmt.Errorf(fmtErrExpectedKey, EventType)
	} else if !c.HasEnvironment() {
		return fmt.Errorf(fmtErrExpectedKey, Environment)
	} else if !c.HasMessageName() {
		return fmt.Errorf(fmtErrExpectedKey, MessageName)
	} else if !c.HasFieldName() {
		return fmt.Errorf(fmtErrExpectedKey, FieldName)
	} else if s, found := c.HasExtraneousKey(); found {
		return fmt.Errorf(fmtErrUnexpectedKey, s)
	}
	return nil
}

func (c Context) HasEventType() bool {
	return c[EventType] != ""
}

func (c Context) HasEnvironment() bool {
	return c[Environment] != ""
}

func (c Context) HasMessageName() bool {
	return c[MessageName] != ""
}

func (c Context) HasFieldName() bool {
	return c[FieldName] != ""
}

func (c Context) HasExtraneousKey() (string, bool) {
	for k := range c {
		switch k {
		case EventType, Environment, MessageName, FieldName:
			continue
		default:
			return k, true
		}
	}
	return "", false
}
