package newshttp

import (
	"fmt"
	authmiddleware "legalgo-BE-go/internal/api/http/middleware/auth"
	newsdomain "legalgo-BE-go/internal/domain/news"
	authsvc "legalgo-BE-go/internal/services/auth"
	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 Update(
	router chi.Router,
	newsSvc newssvc.News,
	authSvc authsvc.Auth,
) {
	router.With(authmiddleware.Authorize()).
		Put("/news/{news_id}/update", func(w http.ResponseWriter, r *http.Request) {
			ctx := r.Context()
			newsID := chi.URLParam(r, "news_id")

			if newsID == "" {
				response.ResponseWithErrorCode(
					ctx,
					w,
					fmt.Errorf("news id is not provided"),
					response.ErrBadRequest.Code,
					response.ErrBadRequest.HttpCode,
					"news id is not provided",
				)
				return
			}

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

			staff, err := authSvc.GetStaffProfile(destructedToken.Email)
			if err != nil {
				response.ResponseWithErrorCode(
					ctx,
					w,
					err,
					response.ErrBadRequest.Code,
					response.ErrBadRequest.HttpCode,
					err.Error(),
				)
				return
			}

			var spec newsdomain.NewsUpdate
			if err := utils.UnmarshalBody(r, &spec); err != nil {
				response.ResponseWithErrorCode(
					ctx,
					w,
					err,
					response.ErrBadRequest.Code,
					response.ErrBadRequest.HttpCode,
					err.Error(),
				)
				return
			}

			spec.ID = newsID

			if err := newsSvc.Update(staff.ID, spec); err != nil {
				response.ResponseWithErrorCode(
					ctx,
					w,
					err,
					response.ErrBadRequest.Code,
					response.ErrBadRequest.HttpCode,
					err.Error(),
				)
				return
			}

			response.RespondJsonSuccess(ctx, w, struct {
				Message string
			}{
				Message: "news updated successfully.",
			})
		})
}
