package mail

import (
	"fmt"
	"net/http"

	"github.com/ultisuite/ulti-backend/internal/api/apiresponse"
	"github.com/ultisuite/ulti-backend/internal/api/apivalidate"
	"github.com/ultisuite/ulti-backend/internal/api/middleware"
)

const maxReorderItems = 500

func validateReorderLabels(req *reorderLabelsRequest) *apivalidate.ValidationError {
	if req == nil || len(req.Items) == 0 {
		return apivalidate.NewValidationError(apivalidate.FieldDetail{Field: "items", Message: "required"})
	}
	if len(req.Items) > maxReorderItems {
		return apivalidate.NewValidationError(apivalidate.FieldDetail{Field: "items", Message: "too many"})
	}
	for i, item := range req.Items {
		if item.ID == "" {
			return apivalidate.NewValidationError(apivalidate.FieldDetail{Field: "items", Message: fmt.Sprintf("id required at index %d", i)})
		}
	}
	return nil
}

func validateReorderUnifiedFolders(req *reorderUnifiedFoldersRequest) *apivalidate.ValidationError {
	if req == nil || len(req.Items) == 0 {
		return apivalidate.NewValidationError(apivalidate.FieldDetail{Field: "items", Message: "required"})
	}
	if len(req.Items) > maxReorderItems {
		return apivalidate.NewValidationError(apivalidate.FieldDetail{Field: "items", Message: "too many"})
	}
	for _, item := range req.Items {
		if item.ID == "" {
			return apivalidate.NewValidationError(apivalidate.FieldDetail{Field: "items", Message: "id required"})
		}
	}
	return nil
}

func (h *Handler) ReorderUserLabels(w http.ResponseWriter, r *http.Request) {
	claims := middleware.ClaimsFromContext(r.Context())
	var req reorderLabelsRequest
	if err := apivalidate.DecodeJSON(w, r, maxUnifiedFolderRequestBody, &req); err != nil {
		return
	}
	if verr := validateReorderLabels(&req); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}
	if err := h.svc.ReorderUserLabels(r.Context(), claims.Sub, &req); err != nil {
		if err == ErrNotFound {
			apivalidate.WriteNotFound(w, r, "not found")
			return
		}
		h.logger.Error("reorder labels", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *Handler) ReorderUnifiedFolders(w http.ResponseWriter, r *http.Request) {
	claims := middleware.ClaimsFromContext(r.Context())
	var req reorderUnifiedFoldersRequest
	if err := apivalidate.DecodeJSON(w, r, maxUnifiedFolderRequestBody, &req); err != nil {
		return
	}
	if verr := validateReorderUnifiedFolders(&req); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}
	if err := h.svc.ReorderUnifiedFolders(r.Context(), claims.Sub, &req); err != nil {
		if err == ErrNotFound {
			apivalidate.WriteNotFound(w, r, "not found")
			return
		}
		if err == ErrInvalidFolderScope {
			apiresponse.WriteError(w, r, http.StatusBadRequest, apiresponse.CodeInvalidRequest, "invalid folder scope", nil)
			return
		}
		h.logger.Error("reorder unified folders", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}
