package mail

import (
	"errors"
	"net/http"

	"github.com/go-chi/chi/v5"

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

func (h *Handler) ListUnifiedFolders(w http.ResponseWriter, r *http.Request) {
	claims := middleware.ClaimsFromContext(r.Context())
	params, err := query.ParseListRequest(r)
	if err != nil {
		apivalidate.WriteQueryError(w, r, err)
		return
	}

	result, err := h.svc.ListUnifiedFolders(r.Context(), claims.Sub, r.URL.Query().Get("account_id"), params)
	if err != nil {
		if errors.Is(err, ErrAccountNotFound) {
			apivalidate.WriteNotFound(w, r, "account not found")
			return
		}
		h.logger.Error("list unified folders", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	apiresponse.WriteJSON(w, http.StatusOK, result)
}

func (h *Handler) CreateUnifiedFolder(w http.ResponseWriter, r *http.Request) {
	claims := middleware.ClaimsFromContext(r.Context())
	userID, err := h.svc.ResolveUserID(r.Context(), claims.Sub)
	if err != nil {
		h.writeUserResolveError(w, r, err)
		return
	}

	var req createUnifiedFolderRequest
	if err := apivalidate.DecodeJSON(w, r, maxUnifiedFolderRequestBody, &req); err != nil {
		return
	}
	if verr := validateCreateUnifiedFolder(&req); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}

	id, err := h.svc.CreateUnifiedFolder(r.Context(), userID, &req)
	if err != nil {
		if errors.Is(err, ErrAccountNotFound) {
			apivalidate.WriteNotFound(w, r, "account not found")
			return
		}
		if errors.Is(err, ErrInvalidFolderScope) {
			apiresponse.WriteError(w, r, http.StatusBadRequest, apiresponse.CodeInvalidRequest, "invalid folder scope", nil)
			return
		}
		h.logger.Error("create unified folder", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	apiresponse.WriteJSON(w, http.StatusCreated, map[string]string{"id": id})
}

func (h *Handler) UpdateUnifiedFolder(w http.ResponseWriter, r *http.Request) {
	claims := middleware.ClaimsFromContext(r.Context())

	var req updateUnifiedFolderRequest
	if err := apivalidate.DecodeJSON(w, r, maxUnifiedFolderRequestBody, &req); err != nil {
		return
	}
	if verr := validateUpdateUnifiedFolder(&req); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}

	err := h.svc.UpdateUnifiedFolder(r.Context(), claims.Sub, chi.URLParam(r, "folderID"), &req)
	if err != nil {
		if errors.Is(err, ErrNotFound) {
			apivalidate.WriteNotFound(w, r, "not found")
			return
		}
		h.logger.Error("update unified folder", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *Handler) DeleteUnifiedFolder(w http.ResponseWriter, r *http.Request) {
	claims := middleware.ClaimsFromContext(r.Context())

	err := h.svc.DeleteUnifiedFolder(r.Context(), claims.Sub, chi.URLParam(r, "folderID"))
	if err != nil {
		if errors.Is(err, ErrNotFound) {
			apivalidate.WriteNotFound(w, r, "not found")
			return
		}
		if errors.Is(err, ErrFolderHasChildren) {
			apiresponse.WriteError(w, r, http.StatusConflict, apiresponse.CodeInvalidRequest, "folder has children", nil)
			return
		}
		h.logger.Error("delete unified folder", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}
