package user

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/dal/errx"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/user"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/logic/user/meta"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/svc"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/entx"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/hander"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/types/core"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/code"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/msg"
	"git.noahlan.cn/noahlan/ntool-biz/core/orm/nent/types"
	"git.noahlan.cn/noahlan/ntool/nlog"
)

type UpdateUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserLogic {
	return &UpdateUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateUserLogic) UpdateUser(in *core.UserInfo) (*core.BaseResp, error) {
	// phoneNumber / email / password 需要单独修改
	if err := entx.WithTx(l.ctx, l.svcCtx.DB, func(tx *ent.Tx) error {
		updated := tx.User.Update().Where(user.IDEQ(in.ID))
		if in.Nickname != nil {
			updated.SetNotEmptyNickname(in.GetNickname())
		}
		// metas
		if len(in.Metas) > 0 {
			userMetaLogic := meta.NewUserMetaLogic(l.ctx, l.svcCtx, tx)
			err := userMetaLogic.UpsetUserMeta(in.ID, in.Metas)
			if err != nil {
				nlog.Errorw("upsert usermeta err", nlog.Field("detail", in), nlog.Field("err", err))
				return nstatus.NewBizErrWithCode(errx.UpdateUserMetaErr)
			}
		}
		// TODO status判定
		updated.SetStatus(types.StatusNormal)
		err := updated.Exec(l.ctx)
		if err != nil {
			return hander.HandleEntErr(err, in)
		}
		return nil
	}); err != nil {
		return nil, err
	}
	return &core.BaseResp{
		Code: code.StatusOK,
		Msg:  msg.UpdateSuccess,
	}, nil
}
