package mocks

import (
	"context"
)

const Error = "error"

type ctxKey string

const awsBehaviorKey = ctxKey("aws-behavior-key")

func IsBehavior(api, result string) func(context.Context) bool {
	return ctxMatcher(api, result)
}

func IsDefaultBehavior(api string) func(context.Context) bool {
	return func(ctx context.Context) bool {
		// only returns tru if the behavior map doesnt have an entry for this API
		m := ctx.Value(awsBehaviorKey)
		if m == nil {
			return true
		}
		// if the API is in the custom behavior map, its not default behavior
		if behaviorMap, ok := m.(map[string]string); ok {
			if _, ok := behaviorMap[api]; ok {
				return false
			}
		}
		return true
	}
}

func ctxMatcher(api, desired string) func(ctx context.Context) bool {
	return func(ctx context.Context) bool {
		// fetch the map
		m := ctx.Value(awsBehaviorKey)
		if m == nil {
			return false
		}
		if behaviorMap, ok := m.(map[string]string); ok {
			if behavior, ok := behaviorMap[api]; ok {
				return behavior == desired
			}
		}
		return false
	}
}

func WithBehavior(ctx context.Context, api, behavior string) context.Context {
	mIface := ctx.Value(awsBehaviorKey)
	var m map[string]string
	var ok bool
	if m, ok = mIface.(map[string]string); !ok {
		m = map[string]string{}
	}
	m[api] = behavior
	return context.WithValue(ctx, awsBehaviorKey, m)
}

func DefaultBehavior() context.Context {
	return context.Background()
}
