package handler

import (
	"net/http"
	"sort"
	"strings"
	"unicode"

	"git.frostfs.info/TrueCloudLab/frostfs-s3-gw/api"
	"git.frostfs.info/TrueCloudLab/frostfs-s3-gw/api/data"
	"git.frostfs.info/TrueCloudLab/frostfs-s3-gw/api/errors"
	"git.frostfs.info/TrueCloudLab/frostfs-s3-gw/api/middleware"
)

const (
	allowedTagChars = "+-=._:/@"

	maxTags           = 10
	keyTagMaxLength   = 128
	valueTagMaxLength = 256
)

func (h *handler) PutObjectTaggingHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	reqInfo := middleware.GetReqInfo(ctx)

	tagSet, err := h.readTagSet(reqInfo.Tagging)
	if err != nil {
		h.logAndSendError(ctx, w, "could not read tag set", reqInfo, err)
		return
	}

	bktInfo, err := h.getBucketAndCheckOwner(r, reqInfo.BucketName)
	if err != nil {
		h.logAndSendError(ctx, w, "could not get bucket info", reqInfo, err)
		return
	}

	tagPrm := &data.PutObjectTaggingParams{
		ObjectVersion: &data.ObjectVersion{
			BktInfo:    bktInfo,
			ObjectName: reqInfo.ObjectName,
			VersionID:  reqInfo.URL.Query().Get(api.QueryVersionID),
		},
		TagSet: tagSet,
	}

	if err = h.obj.PutObjectTagging(ctx, tagPrm); err != nil {
		h.logAndSendError(ctx, w, "could not put object tagging", reqInfo, err)
		return
	}

	w.WriteHeader(http.StatusOK)
}

func (h *handler) GetObjectTaggingHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	reqInfo := middleware.GetReqInfo(ctx)

	bktInfo, err := h.getBucketAndCheckOwner(r, reqInfo.BucketName)
	if err != nil {
		h.logAndSendError(ctx, w, "could not get bucket info", reqInfo, err)
		return
	}

	settings, err := h.obj.GetBucketSettings(ctx, bktInfo)
	if err != nil {
		h.logAndSendError(ctx, w, "could not get bucket settings", reqInfo, err)
		return
	}

	tagPrm := &data.GetObjectTaggingParams{
		ObjectVersion: &data.ObjectVersion{
			BktInfo:    bktInfo,
			ObjectName: reqInfo.ObjectName,
			VersionID:  reqInfo.URL.Query().Get(api.QueryVersionID),
		},
	}

	versionID, tagSet, err := h.obj.GetObjectTagging(ctx, tagPrm)
	if err != nil {
		h.logAndSendError(ctx, w, "could not get object tagging", reqInfo, err)
		return
	}

	if settings.VersioningEnabled() {
		w.Header().Set(api.AmzVersionID, versionID)
	}
	if err = middleware.EncodeToResponse(w, encodeTagging(tagSet)); err != nil {
		h.logAndSendError(ctx, w, "something went wrong", reqInfo, err)
	}
}

func (h *handler) DeleteObjectTaggingHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	reqInfo := middleware.GetReqInfo(ctx)

	bktInfo, err := h.getBucketAndCheckOwner(r, reqInfo.BucketName)
	if err != nil {
		h.logAndSendError(ctx, w, "could not get bucket info", reqInfo, err)
		return
	}

	p := &data.ObjectVersion{
		BktInfo:    bktInfo,
		ObjectName: reqInfo.ObjectName,
		VersionID:  reqInfo.URL.Query().Get(api.QueryVersionID),
	}

	if err = h.obj.DeleteObjectTagging(ctx, p); err != nil {
		h.logAndSendError(ctx, w, "could not delete object tagging", reqInfo, err)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}

func (h *handler) PutBucketTaggingHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	reqInfo := middleware.GetReqInfo(ctx)

	tagSet, err := h.readTagSet(reqInfo.Tagging)
	if err != nil {
		h.logAndSendError(ctx, w, "could not read tag set", reqInfo, err)
		return
	}

	bktInfo, err := h.getBucketAndCheckOwner(r, reqInfo.BucketName)
	if err != nil {
		h.logAndSendError(ctx, w, "could not get bucket info", reqInfo, err)
		return
	}

	if err = h.obj.PutBucketTagging(ctx, bktInfo, tagSet); err != nil {
		h.logAndSendError(ctx, w, "could not put object tagging", reqInfo, err)
		return
	}
}

func (h *handler) GetBucketTaggingHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	reqInfo := middleware.GetReqInfo(ctx)

	bktInfo, err := h.getBucketAndCheckOwner(r, reqInfo.BucketName)
	if err != nil {
		h.logAndSendError(ctx, w, "could not get bucket info", reqInfo, err)
		return
	}

	tagSet, err := h.obj.GetBucketTagging(ctx, bktInfo)
	if err != nil {
		h.logAndSendError(ctx, w, "could not get object tagging", reqInfo, err)
		return
	}

	if err = middleware.EncodeToResponse(w, encodeTagging(tagSet)); err != nil {
		h.logAndSendError(ctx, w, "something went wrong", reqInfo, err)
		return
	}
}

func (h *handler) DeleteBucketTaggingHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	reqInfo := middleware.GetReqInfo(ctx)

	bktInfo, err := h.getBucketAndCheckOwner(r, reqInfo.BucketName)
	if err != nil {
		h.logAndSendError(ctx, w, "could not get bucket info", reqInfo, err)
		return
	}

	if err = h.obj.DeleteBucketTagging(ctx, bktInfo); err != nil {
		h.logAndSendError(ctx, w, "could not delete bucket tagging", reqInfo, err)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *handler) readTagSet(tagging *data.Tagging) (map[string]string, error) {
	if err := checkTagSet(tagging.TagSet); err != nil {
		return nil, err
	}

	tagSet := make(map[string]string, len(tagging.TagSet))
	for _, tag := range tagging.TagSet {
		if _, ok := tagSet[tag.Key]; ok {
			return nil, errors.GetAPIError(errors.ErrInvalidTagKeyUniqueness)
		}
		tagSet[tag.Key] = tag.Value
	}

	return tagSet, nil
}

func encodeTagging(tagSet map[string]string) *data.Tagging {
	tagging := &data.Tagging{}
	for k, v := range tagSet {
		tagging.TagSet = append(tagging.TagSet, data.Tag{Key: k, Value: v})
	}
	sort.Slice(tagging.TagSet, func(i, j int) bool {
		return tagging.TagSet[i].Key < tagging.TagSet[j].Key
	})

	return tagging
}

func checkTagSet(tagSet []data.Tag) error {
	if len(tagSet) > maxTags {
		return errors.GetAPIError(errors.ErrInvalidTagsSizeExceed)
	}

	for _, tag := range tagSet {
		if err := checkTag(tag); err != nil {
			return err
		}
	}

	return nil
}

func checkTag(tag data.Tag) error {
	if len(tag.Key) < 1 || len(tag.Key) > keyTagMaxLength {
		return errors.GetAPIError(errors.ErrInvalidTagKey)
	}
	if len(tag.Value) > valueTagMaxLength {
		return errors.GetAPIError(errors.ErrInvalidTagValue)
	}

	if strings.HasPrefix(tag.Key, "aws:") {
		return errors.GetAPIError(errors.ErrInvalidTagKey)
	}

	if !isValidTag(tag.Key) {
		return errors.GetAPIError(errors.ErrInvalidTagKey)
	}
	if !isValidTag(tag.Value) {
		return errors.GetAPIError(errors.ErrInvalidTagValue)
	}

	return nil
}

func isValidTag(str string) bool {
	for _, r := range str {
		if !unicode.IsLetter(r) && !unicode.IsDigit(r) &&
			!unicode.IsSpace(r) && !strings.ContainsRune(allowedTagChars, r) {
			return false
		}
	}
	return true
}