package auth

import (
	"backend/internal/domain"
	"backend/internal/logic/auth"
	"backend/internal/svc"
	"backend/internal/types"
	"backend/pkg/library/errs"
	ers "backend/pkg/library/errs"
	"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.InvalidFormat(err.Error())
			httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.RespOK{
				Code: int(e.FullCode()),
				Msg:  err.Error(),
			})

			return
		}

		//if err := svcCtx.Validate.ValidateAll(req); err != nil {
		//	e := errs.InvalidFormat(err.Error())
		//	httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.RespOK{
		//		Code: int(e.FullCode()),
		//		Msg:  err.Error(),
		//	})
		//
		//	return
		//}

		l := auth.NewLoginLogic(r.Context(), svcCtx)
		resp, err := l.Login(&req)
		if err != nil {
			e := ers.FromError(err)
			httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.ErrorResp{
				Code:  int(e.FullCode()),
				Msg:   e.Error(),
				Error: e,
			})
		} else {
			httpx.WriteJsonCtx(r.Context(), w, http.StatusOK, types.RespOK{
				Code: domain.SuccessCode,
				Msg:  domain.SuccessMessage,
				Data: resp,
			})
		}
	}
}
