package admin

import (
	"errors"
	"net/http"
	"strings"

	"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) ListUserGroups(w http.ResponseWriter, r *http.Request) {
	params, err := query.ParseListRequest(r)
	if err != nil {
		apivalidate.WriteQueryError(w, r, err)
		return
	}
	result, err := h.svc.ListUserGroups(r.Context(), params)
	if err != nil {
		h.logger.Error("list user groups", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	apiresponse.WriteJSON(w, http.StatusOK, result)
}

func (h *Handler) GetUserGroup(w http.ResponseWriter, r *http.Request) {
	groupID := chi.URLParam(r, "groupID")
	if verr := validateGroupID(groupID); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}
	group, err := h.svc.GetUserGroup(r.Context(), groupID)
	if err != nil {
		if errors.Is(err, ErrNotFound) {
			apivalidate.WriteNotFound(w, r, "not found")
			return
		}
		h.logger.Error("get user group", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	apiresponse.WriteJSON(w, http.StatusOK, group)
}

func (h *Handler) CreateUserGroup(w http.ResponseWriter, r *http.Request) {
	claims := middleware.ClaimsFromContext(r.Context())
	var req createUserGroupRequest
	if err := apivalidate.DecodeJSON(w, r, maxQuotaRequestBody, &req); err != nil {
		return
	}
	if verr := validateCreateUserGroup(&req); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}
	group, err := h.svc.CreateUserGroup(r.Context(), claims.Sub, req)
	if err != nil {
		if errors.Is(err, ErrGroupNameTaken) {
			apivalidate.WriteValidationError(w, r, apivalidate.NewValidationError(
				apivalidate.FieldDetail{Field: "name", Message: "already exists"},
			))
			return
		}
		h.logger.Error("create user group", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	apiresponse.WriteJSON(w, http.StatusCreated, group)
}

func (h *Handler) UpdateUserGroup(w http.ResponseWriter, r *http.Request) {
	groupID := chi.URLParam(r, "groupID")
	if verr := validateGroupID(groupID); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}
	claims := middleware.ClaimsFromContext(r.Context())
	var req updateUserGroupRequest
	if err := apivalidate.DecodeJSON(w, r, maxQuotaRequestBody, &req); err != nil {
		return
	}
	if verr := validateUpdateUserGroup(&req); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}
	group, err := h.svc.UpdateUserGroup(r.Context(), claims.Sub, groupID, req)
	if err != nil {
		if errors.Is(err, ErrNotFound) {
			apivalidate.WriteNotFound(w, r, "not found")
			return
		}
		if errors.Is(err, ErrGroupNameTaken) {
			apivalidate.WriteValidationError(w, r, apivalidate.NewValidationError(
				apivalidate.FieldDetail{Field: "name", Message: "already exists"},
			))
			return
		}
		h.logger.Error("update user group", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	apiresponse.WriteJSON(w, http.StatusOK, group)
}

func (h *Handler) DeleteUserGroup(w http.ResponseWriter, r *http.Request) {
	groupID := chi.URLParam(r, "groupID")
	if verr := validateGroupID(groupID); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}
	claims := middleware.ClaimsFromContext(r.Context())
	if err := h.svc.DeleteUserGroup(r.Context(), claims.Sub, groupID); err != nil {
		if errors.Is(err, ErrNotFound) {
			apivalidate.WriteNotFound(w, r, "not found")
			return
		}
		h.logger.Error("delete user group", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (h *Handler) SetUserGroupMembers(w http.ResponseWriter, r *http.Request) {
	groupID := chi.URLParam(r, "groupID")
	if verr := validateGroupID(groupID); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}
	claims := middleware.ClaimsFromContext(r.Context())
	var req setGroupMembersRequest
	if err := apivalidate.DecodeJSON(w, r, maxQuotaRequestBody, &req); err != nil {
		return
	}
	group, err := h.svc.SetGroupMembers(r.Context(), claims.Sub, groupID, req)
	if err != nil {
		if errors.Is(err, ErrNotFound) {
			apivalidate.WriteNotFound(w, r, "not found")
			return
		}
		h.logger.Error("set user group members", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	apiresponse.WriteJSON(w, http.StatusOK, group)
}

func (h *Handler) BulkUsersAction(w http.ResponseWriter, r *http.Request) {
	claims := middleware.ClaimsFromContext(r.Context())
	var req bulkUsersRequest
	if err := apivalidate.DecodeJSON(w, r, maxQuotaRequestBody, &req); err != nil {
		return
	}
	if verr := validateBulkUsers(&req); verr != nil {
		apivalidate.WriteValidationError(w, r, verr)
		return
	}
	result, err := h.svc.BulkUsersAction(r.Context(), claims.Sub, req)
	if err != nil {
		if strings.Contains(err.Error(), "invalid action") {
			apivalidate.WriteValidationError(w, r, apivalidate.NewValidationError(
				apivalidate.FieldDetail{Field: "action", Message: "invalid"},
			))
			return
		}
		if strings.Contains(err.Error(), "group_id required") {
			apivalidate.WriteValidationError(w, r, apivalidate.NewValidationError(
				apivalidate.FieldDetail{Field: "group_id", Message: "required"},
			))
			return
		}
		if strings.Contains(err.Error(), "no user ids") {
			apivalidate.WriteValidationError(w, r, apivalidate.NewValidationError(
				apivalidate.FieldDetail{Field: "user_ids", Message: "required"},
			))
			return
		}
		h.logger.Error("bulk users action", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	apiresponse.WriteJSON(w, http.StatusOK, result)
}
