package handler

import (
	"bytes"
	"fmt"

	"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
	"git.frostfs.info/TrueCloudLab/frostfs-http-gw/utils"
	"github.com/valyala/fasthttp"
	"go.uber.org/zap"
)

func filterHeaders(l *zap.Logger, header *fasthttp.RequestHeader) (map[string]string, error) {
	var err error
	result := make(map[string]string)
	prefix := []byte(utils.UserAttributeHeaderPrefix)

	header.VisitAll(func(key, val []byte) {
		// checks that the key and the val not empty
		if len(key) == 0 || len(val) == 0 {
			return
		}

		// checks that the key has attribute prefix
		if !bytes.HasPrefix(key, prefix) {
			return
		}

		// removing attribute prefix
		clearKey := bytes.TrimPrefix(key, prefix)

		clearKey = utils.TransformIfSystem(clearKey)

		// checks that the attribute key is not empty
		if len(clearKey) == 0 {
			return
		}

		// check if key gets duplicated
		// return error containing full key name (with prefix)
		if _, ok := result[string(clearKey)]; ok {
			err = fmt.Errorf("key duplication error: %s", string(key))
			return
		}

		// make string representation of key / val
		k, v := string(clearKey), string(val)

		result[k] = v

		l.Debug(logs.AddAttributeToResultObject,
			zap.String("key", k),
			zap.String("val", v))
	})

	return result, err
}