package auth

import (
	"backend/internal/logic/auth"
	"backend/internal/svc"
	"backend/internal/types"
	errs "backend/pkg/library/errors"
	"net/http"

	"github.com/zeromicro/go-zero/rest/httpx"
)

// 使用者登入
func LoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.LoginReq
		if err := httpx.Parse(r, &req); err != nil {
			e := errs.InputInvalidFormatError(err.Error())
			httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.Resp{
				Code:    e.DisplayCode(),
				Message: err.Error(),
			})

			return
		}

		//if err := svcCtx.Validate.ValidateAll(req); err != nil {
		//	e := errs.InputInvalidRangeError(err.Error())
		//	httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.Resp{
		//		Code:    e.DisplayCode(),
		//		Message: err.Error(),
		//		Error:   err,
		//	})
		//
		//	return
		//}

		l := auth.NewLoginLogic(r.Context(), svcCtx)
		resp, err := l.Login(&req)
		if err != nil {
			e := errs.FromError(err)
			httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.Resp{
				Code:    e.DisplayCode(),
				Message: e.Error(),
				Error:   e.Unwrap(),
			})
		} else {
			httpx.WriteJsonCtx(r.Context(), w, http.StatusOK, resp)
		}
	}
}
