package subscribehttp

import (
	authmiddleware "legalgo-BE-go/internal/api/http/middleware/auth"
	userdomain "legalgo-BE-go/internal/domain/user"
	authsvc "legalgo-BE-go/internal/services/auth"
	subscribesvc "legalgo-BE-go/internal/services/subscribe"
	"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,
	authSvc authsvc.Auth,
	subSvc subscribesvc.Subscribe,
) {
	router.
		With(authmiddleware.Authorize()).
		Patch("/subscribe/update", func(w http.ResponseWriter, r *http.Request) {
			ctx := r.Context()

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

			if detail.Role != "user" {
				response.ResponseWithErrorCode(
					ctx,
					w,
					err,
					response.ErrUnauthorized.Code,
					response.ErrUnauthorized.HttpCode,
					"unauthorized",
				)
				return
			}
			var body userdomain.UserSubsUpdate
			err = utils.UnmarshalBody(r, &body)
			if err != nil {
				response.ResponseWithErrorCode(
					ctx,
					w,
					err,
					response.ErrBadRequest.Code,
					response.ErrBadRequest.HttpCode,
					err.Error(),
				)
				return
			}

			user, err := authSvc.GetUserProfile(detail.Email)

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