package userhttp

import (
	responsedomain "legalgo-BE-go/internal/domain/reponse"
	userdomain "legalgo-BE-go/internal/domain/user"
	usersvc "legalgo-BE-go/internal/services/user"
	"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"
	"github.com/redis/go-redis/v9"
)

func Login(
	router chi.Router,
	userSvc usersvc.User,
	validate *validator.Validate,
	rdb *redis.Client,
) {
	router.Post("/user/login", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		var spec userdomain.UserLogin

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

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

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

		if err := utils.StoreTokenRedis(ctx, rdb, token, spec.Email); err != nil {
			response.ResponseWithErrorCode(
				ctx,
				w,
				err,
				response.ErrBadRequest.Code,
				response.ErrBadRequest.HttpCode,
				err.Error(),
			)
			return
		}

		responsePayload := &responsedomain.Auth{
			Token: token,
		}

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