package http_router

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

	"git-molva.ru/Molva/molva-backend/services/api_gateway/internal/constants"
	rmodel "git-molva.ru/Molva/molva-backend/services/api_gateway/internal/request_model"
	"github.com/gorilla/mux"
)

func (h *handler) getCompanyListDistributorHandler(w http.ResponseWriter, r *http.Request) {
	const handlerName = "getCompanyListDistributorHandler"

	var (
		vars   = mux.Vars(r)
		distId = vars["distributor_id"]
	)

	result, err := h.distributorService.GetCompanyList(r.Context(), &rmodel.CompanyListGetRequest{
		Id: distId,
	})
	if err != nil {
		h.handleDistributorError(w, err)
		h.logger.Error("error getting company list",
			slog.String("error", err.Error()),
			slog.String("handler", handlerName),
		)

		return
	}

	w.Header().Set("Content-Type", "application/json")

	if err := json.NewEncoder(w).Encode(result); err != nil {
		http.Error(w, constants.ErrInternalServerError.Error(), http.StatusInternalServerError)
		h.logger.Error("error encoding response",
			slog.String("error", err.Error()),
			slog.String("handler", handlerName),
		)
	}
}

func (h *handler) getCompanyByIdDistributorHandler(w http.ResponseWriter, r *http.Request) {
	const handlerName = "getCompanyByIdDistributorHandler"

	var (
		vars      = mux.Vars(r)
		distId    = vars["distributor_id"]
		companyId = vars["company_id"]
	)

	result, err := h.distributorService.GetCompanyInfoById(r.Context(), &rmodel.CompanyByIdGetRequest{
		UserId:    distId,
		CompanyId: companyId,
	})
	if err != nil {
		h.handleDistributorError(w, err)
		h.logger.Error("error getting company list",
			slog.String("error", err.Error()),
			slog.String("handler", handlerName),
		)

		return
	}

	w.Header().Set("Content-Type", "application/json")

	if err := json.NewEncoder(w).Encode(result); err != nil {
		http.Error(w, constants.ErrInternalServerError.Error(), http.StatusInternalServerError)
		h.logger.Error("error encoding response",
			slog.String("error", err.Error()),
			slog.String("handler", handlerName),
		)
	}
}

func (h *handler) createCompanyDistributorHandler(w http.ResponseWriter, r *http.Request) {
	const handlerName = "createCompanyDistributorHandler"

	var (
		vars   = mux.Vars(r)
		distId = vars["distributor_id"]
	)

	var request rmodel.CompanyCreateRequest

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

		return
	}

	request.OwnerId = distId

	result, err := h.distributorService.CreateCompany(r.Context(), &request)
	if err != nil {
		h.handleDistributorError(w, err)
		h.logger.Error("error creating company",
			slog.String("error", err.Error()),
			slog.String("handler", handlerName),
		)

		return
	}

	// TODO:
	// h.createCreateCompanyFeedEvent(r.Context(), distId, false, resp, handlerName)

	w.WriteHeader(http.StatusCreated)
	w.Header().Set("Content-Type", "application/json")

	if err := json.NewEncoder(w).Encode(result); err != nil {
		http.Error(w, constants.ErrInternalServerError.Error(), http.StatusInternalServerError)
		h.logger.Error("error encoding response",
			slog.String("error", err.Error()),
			slog.String("handler", handlerName),
		)
	}
}

func (h *handler) updateCompanyDistributorHandler(w http.ResponseWriter, r *http.Request) {
	const handlerName = "updateCompanyDistributorHandler"

	var (
		vars      = mux.Vars(r)
		companyId = vars["company_id"]
	)

	var request rmodel.CompanyUpdateRequest

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

		return
	}

	request.Id = companyId

	if _, err := h.distributorService.UpdateCompanyInfo(r.Context(), &request); err != nil {
		h.handleDistributorError(w, err)
		h.logger.Error("error updating company info",
			slog.String("error", err.Error()),
			slog.String("handler", handlerName),
		)

		return
	}

	// BUG: holds request for infinite time
	// h.createEditCompanyFeedEvent(r.Context(), distId, false, comId, handlerName)

	w.WriteHeader(http.StatusNoContent)
}

func (h *handler) addCompanyMemberDistributorHandler(w http.ResponseWriter, r *http.Request) {
	const handlerName = "addCompanyMemberDistributorHandler"

	var (
		vars      = mux.Vars(r)
		companyId = vars["company_id"]
	)

	var request rmodel.AddDistributorCompanyMemberRequest

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

		return
	}

	request.CompanyId = companyId

	if _, err := h.distributorService.AddEmployee(r.Context(), &request); err != nil {
		h.handleDistributorError(w, err)
		h.logger.Error("error adding new staff member",
			slog.String("error", err.Error()),
			slog.String("handler", handlerName),
		)

		return
	}

	// TODO:
	// h.createAddNewStaffMemberFeedEvent(r.Context(), distId, true, *req.NewStaffMember, companyId, handlerName)

	w.WriteHeader(http.StatusNoContent)
}
