package newshttp

import (
	logsdomain "legalgo-BE-go/internal/domain/logs"
	logssvc "legalgo-BE-go/internal/services/logs"
	newssvc "legalgo-BE-go/internal/services/news"
	"legalgo-BE-go/internal/utilities/response"
	"legalgo-BE-go/internal/utilities/utils"
	"net/http"

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

func GetBySlug(
	router chi.Router,
	newsSvc newssvc.News,
	logSvc logssvc.Log,
) {
	router.Get("/news/{slug}", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		slug := chi.URLParam(r, "slug")

		news, err := newsSvc.GetBySlug(slug)
		if err != nil {
			response.ResponseWithErrorCode(
				ctx,
				w,
				err,
				response.ErrBadRequest.Code,
				response.ErrBadRequest.HttpCode,
				err.Error(),
			)
			return
		}

		userDetail, _ := utils.GetTokenDetail(r)

		if userDetail.Role != "staff" {
			var specReq logsdomain.LogsSpec

			specReq.ContentID = news.ID

			if userDetail.ID != "" {
				specReq.UserID = &userDetail.ID
			}

			if ip := r.Header.Get("X-Ip-Address"); ip != "" {
				specReq.IP = &ip
			}

			if userAgent := r.Header.Get("X-User-Agent"); userAgent != "" {
				specReq.UserAgent = &userAgent
			}

			if err := logSvc.CreateLogNews(specReq); err != nil {
				response.RespondJsonErrorWithCode(
					ctx,
					w,
					err,
					response.ErrBadRequest.Code,
					response.ErrBadRequest.HttpCode,
					err.Error(),
				)
				return
			}
		}

		response.RespondJsonSuccess(ctx, w, news)
	})
}
