package login_record

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/loginrecord"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/hander"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/code"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/msg"
	"git.noahlan.cn/noahlan/ntool/ntime"
	"time"

	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/svc"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/types/core"
)

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

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

func (l *RecordLogic) Record(in *core.LoginRecordInfo) (*core.BaseResp, error) {
	err := l.svcCtx.DB.LoginRecord.Create().
		SetUserID(in.UserId).
		SetLastLoginAt(ntime.MustParseTimeD(in.LastLoginAt, time.Now(), time.DateTime)).
		SetLastLoginIpv4(in.LastLoginIpv4).
		SetLastLoginDevice(in.LastLoginDevice).
		SetLastLoginUA(in.LastLoginUa).
		// upsert
		OnConflictColumns(loginrecord.UserColumn).
		Update(func(upsert *ent.LoginRecordUpsert) {
			upsert.UpdateLastLoginAt().
				UpdateLastLoginIpv4().
				UpdateLastLoginDevice().
				UpdateLastLoginUA().
				SetUpdatedAt(time.Now()).
				AddLoginCount(1).
				AddVersion(1)
		}).
		Exec(l.ctx)
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}
	return &core.BaseResp{
		Code: code.StatusOK,
		Msg:  msg.Success,
	}, nil
}
