package user_social

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/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"
)

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

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

// User Management
func (l *CreateUserSocialLogic) CreateUserSocial(in *core.UserSocialInfo) (*core.BaseIDResp, error) {
	var dbData *ent.UserSocial
	if err := entx.WithTx(l.ctx, l.svcCtx.DB, func(tx *ent.Tx) error {
		var err error
		if err := l.preCheck(tx, in); err != nil {
			return err
		}
		create := tx.UserSocial.Create()
		create.SetProvider(in.Provider).
			SetAccessToken(in.AccessToken).
			SetRefreshToken(in.RefreshToken).
			SetUID(in.Uid).
			SetOpenID(in.OpenId).
			SetUnionID(in.UnionId).
			SetKey(in.Key).
			SetExpiresIn(in.ExpiresIn).
			SetUserProfile(in.UserProfile)
		if in.UserId != 0 {
			create.SetUserID(in.UserId)
		}
		dbData, err = create.Save(l.ctx)
		if err != nil {
			return hander.HandleEntErr(err, in)
		}
		return nil
	}); err != nil {
		return nil, err
	}
	return &core.BaseIDResp{
		ID:   dbData.ID,
		Code: code.StatusOK,
		Msg:  msg.CreateSuccess,
	}, nil
}

func (l *CreateUserSocialLogic) preCheck(tx *ent.Tx, in *core.UserSocialInfo) error {
	if in.UserId == 0 {
		return nstatus.NewBizErrWithCode(errx.UserSocialUserIdNotEmpty)
	}
	return nil
}
