package newshttp

import (
	authmiddleware "legalgo-BE-go/internal/api/http/middleware/auth"
	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 GetByID(
	router chi.Router,
	newsSvc newssvc.News,
	logSvc logssvc.Log,
) {
	router.With(authmiddleware.Authorize()).Get("/staff/news/{id}", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		id := chi.URLParam(r, "id")

		token, err := utils.GetToken(r)
		if err != nil {
			response.ResponseWithErrorCode(
				ctx,
				w,
				err,
				response.ErrBadRequest.Code,
				response.ErrBadRequest.HttpCode,
				err.Error(),
			)
			return
		}

		staffDetail, err := utils.DestructToken(token)

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

		if staffDetail.Role != "staff" {
			response.ResponseWithErrorCode(
				ctx,
				w,
				err,
				response.ErrUnauthorized.Code,
				response.ErrUnauthorized.HttpCode,
				"unauthorized",
			)
			return
		}

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

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