package logshttp

import (
	logsdomain "legalgo-BE-go/internal/domain/logs"
	logssvc "legalgo-BE-go/internal/services/logs"
	usersvc "legalgo-BE-go/internal/services/user"
	"legalgo-BE-go/internal/utilities/response"
	"legalgo-BE-go/internal/utilities/utils"
	"net/http"
	"strings"

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

func CreateLogAds(
	router chi.Router,
	userSvc usersvc.User,
	logsSvc logssvc.Log,
	validate *validator.Validate,
) {
	router.Post("/logs/ads", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		var specReq logsdomain.LogsSpec

		var spec logsdomain.LogsRequest

		if err := utils.UnmarshalBody(r, &spec); err != nil {
			response.RespondJsonErrorWithCode(
				ctx,
				w,
				err,
				response.ErrBadRequest.Code,
				response.ErrBadRequest.HttpCode,
				"failed 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
		}

		specReq.ContentID = spec.AdsID

		userDetail, _ := utils.GetTokenDetail(r)

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

		ip := r.RemoteAddr

		if forwarded := r.Header.Get("X-Forwarded-For"); forwarded != "" {
			ip = strings.Split(forwarded, ",")[0]
		}

		if ip != "" {
			specReq.IP = &ip
		}

		if userAgent := r.UserAgent(); userAgent != "" {
			specReq.UserAgent = &userAgent
		}

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

		response.RespondJsonSuccess(ctx, w, struct {
			Message string
		}{
			Message: "logs ads recorded successfully",
		})
	})
}
