package user

import (
	errs "backend/pkg/library/errors"
	"net/http"

	"backend/internal/logic/user"
	"backend/internal/svc"
	"backend/internal/types"

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

// 請求發送驗證碼 (用於驗證信箱/手機)
func RequestVerificationCodeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.RequestVerificationCodeReq
		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
		}

		l := user.NewRequestVerificationCodeLogic(r.Context(), svcCtx)
		resp, err := l.RequestVerificationCode(&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)
		}
	}
}
