package http_router

import (
	"encoding/json"
	"log/slog"
	"net/http"

	"git-molva.ru/Molva/molva-backend/services/api_gateway/internal/constants"
	dbtypes "git-molva.ru/Molva/molva-backend/services/api_gateway/internal/database/types"
	"git-molva.ru/Molva/molva-backend/services/api_gateway/internal/integration"
	intrmodel "git-molva.ru/Molva/molva-backend/services/api_gateway/internal/request_model/integration"
)

// @Summary Callback интеграции с ВкусВилл
// @Description Обработка callback запросов от интеграции с ВкусВилл
// @Tags integration
// @Accept json
// @Produce json
// @Param request body map[string]interface{} true "Данные callback от ВкусВилл"
// @Success 200 {object} map[string]string "Callback обработан"
// @Failure 400 {object} map[string]string "Неверные данные запроса"
// @Failure 500 {object} map[string]string "Внутренняя ошибка сервера"
// @Router /api/v1/integration/vkusvill/callback [post]
func (h *handler) vkusvillIntegrationCallbackHandler(w http.ResponseWriter, r *http.Request) {
	const handlerName = "vkusvillIntegrationCallbackHandler"

	var request intrmodel.VkusvillSaveCandidateCallbackRequest

	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		http.Error(w, constants.ErrBadRequest.Error(), http.StatusBadRequest)
		h.logger.Error("error while decoding request body",
			slog.String("error", err.Error()),
			slog.String("handler", handlerName))

		return
	}

	defer r.Body.Close()

	h.logger.Debug("vkusvill integration callback request received",
		slog.String("message", request.Message),
		slog.String("handler", handlerName),
	)

	status, err := integration.VkusvillGetCandidateStatus(request.Params.Status)
	if err != nil {
		http.Error(w, constants.ErrBadRequest.Error(), http.StatusBadRequest)
		h.logger.Error("error getting vkusvill candidate status",
			slog.String("error", err.Error()),
			slog.String("handler", handlerName))

		return
	}

	if _, err := h.dbClient.UpdateSubmissionStatus(r.Context(), &dbtypes.SubmissionStatusUpdateRequest{
		Id:     request.Params.CandidateId,
		Status: *dbtypes.NewSubmissionStatus(status.NullString()),
	}); err != nil {
		http.Error(w, constants.ErrInternalServerError.Error(), http.StatusInternalServerError)
		h.logger.Error("error while building and processing request: ",
			slog.String("error", err.Error()),
			slog.String("handler", handlerName))

		return
	}

	// TODO: add event to feed
	// go ...

	w.WriteHeader(http.StatusAccepted)
}
