package subscribeplanhttp

import (
	"fmt"
	authmiddleware "legalgo-BE-go/internal/api/http/middleware/auth"
	subscribeplandomain "legalgo-BE-go/internal/domain/subscribe_plan"
	subscribeplansvc "legalgo-BE-go/internal/services/subscribe_plan"
	"legalgo-BE-go/internal/utilities/response"
	"legalgo-BE-go/internal/utilities/utils"
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/go-playground/validator/v10"
)

func Update(
	router chi.Router,
	validate *validator.Validate,
	subsPlanSvc subscribeplansvc.SubscribePlan,
) {
	router.
		With(authmiddleware.Authorize()).
		Put("/subscribe-plan/{subsplan_id}/update", func(w http.ResponseWriter, r *http.Request) {
			ctx := r.Context()
			tagID := chi.URLParam(r, "subsplan_id")

			if tagID == "" {
				response.RespondJsonErrorWithCode(
					ctx,
					w,
					fmt.Errorf("subscribe plan id is not provided"),
					response.ErrBadRequest.Code,
					response.ErrBadRequest.HttpCode,
					"subscribe plan id is not provided",
				)
				return
			}

			var spec subscribeplandomain.SubscribePlanUpdate
			if err := utils.UnmarshalBody(r, &spec); err != nil {
				response.RespondJsonErrorWithCode(
					ctx,
					w,
					err,
					response.ErrBadRequest.Code,
					response.ErrBadRequest.HttpCode,
					"failed to unmarshal body",
				)
				return
			}

			if err := validate.Struct(spec); err != nil {
				response.RespondJsonErrorWithCode(
					ctx,
					w,
					err,
					response.ErrBadRequest.Code,
					response.ErrBadRequest.HttpCode,
					err.(validator.ValidationErrors).Error(),
				)
				return
			}

			if err := subsPlanSvc.Update(tagID, spec); err != nil {
				response.RespondJsonErrorWithCode(
					ctx,
					w,
					err,
					response.ErrBadRequest.Code,
					response.ErrBadRequest.HttpCode,
					err.Error(),
				)
				return
			}

			response.RespondJsonSuccess(ctx, w, struct {
				Message string
			}{
				Message: "update subscribe plan success",
			})
		})
}
