package meta

import (
	"context"
	"entgo.io/ent/dialect/sql"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/svc"
)

type UserMetaLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	tx     *ent.Tx
}

func NewUserMetaLogic(ctx context.Context, svcCtx *svc.ServiceContext, tx *ent.Tx) *UserMetaLogic {
	return &UserMetaLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		tx:     tx,
	}
}

func (l *UserMetaLogic) getDBClient() *ent.UserMetaClient {
	if l.tx != nil {
		return l.tx.UserMeta
	}
	return l.svcCtx.DB.UserMeta
}

func (l *UserMetaLogic) UpsetUserMeta(userId int64, metaMap map[string]string) error {
	db := l.getDBClient()

	bulk := make([]*ent.UserMetaCreate, 0)
	for k, v := range metaMap {
		bulk = append(bulk, db.Create().
			SetUserID(userId).
			SetKey(k).
			SetValue(v))
	}

	err := db.CreateBulk(bulk...).
		OnConflict(sql.ResolveWithNewValues()).
		Exec(l.ctx)

	if err != nil {
		return err
	}
	return nil
}
