package auth

import (
	"backend/internal/domain"
	"backend/pkg/library/errs"
	"net/http"

	"backend/internal/logic/auth"
	"backend/internal/svc"
	"backend/internal/types"

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

// 註冊新帳號
func RegisterHandler(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.NewRegisterLogic(r.Context(), svcCtx)
		resp, err := l.Register(&req)
		if err != nil {
			e := errs.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,
			})
		}
	}
}
