package openapi

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"strings"
)

func CheckOperatorAuthorization(r *http.Request, authorizedOperators map[string]string) bool {
	authorizationHeader := r.Header.Get("Authorization")
	if authorizationHeader == "" {
		return false
	}
	parts := strings.Split(authorizationHeader, " ")
	if len(parts) != 2 {
		return false
	}
	if parts[0] != "Bearer" {
		return false
	}
	apiKey := parts[1]
	operatorName, authorized := authorizedOperators[apiKey]
	var operator string
	var found bool

	if r.Body != nil {
		body, err := ioutil.ReadAll(r.Body)
		if err == nil {
			var payload map[string]interface{}
			if json.Unmarshal(body, &payload) == nil {
				// Check for "operator" in the top-level body
				if op, ok := payload["operator"].(string); ok {
					operator = op
					found = true
				} else {
					// Check for "user" struct in the body
					if user, ok := payload["user"].(map[string]interface{}); ok {
						if op, ok := user["operator"].(string); ok {
							operator = op
							found = true
						}
					}
				}
			}
		}
		r.Body = ioutil.NopCloser(bytes.NewReader(body))
	}

	// If operator is not found in the request body, check the request parameters.
	if !found {
		operatorFromParams := r.URL.Query().Get("operator")
		if operatorFromParams != "" {
			operator = operatorFromParams
			found = true
		}
	}

	if found && operator == operatorName && authorized {
		return true
	}
	return false
}

var AuthorizedOperators = map[string]string{
	"$2y$10$TJuDZDu.mqy5dDKGMSfxSO5f6pz/36XVrAyQ1CXJd63ccjRlX7lmK": "test.com",
}
