package token

import (
	"context"
	"github.com/zeromicro/go-zero/core/errorx"
	"time"
	"wechat-api/ent"
	"wechat-api/ent/token"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateTokenLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateTokenLogic {
	return &UpdateTokenLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateTokenLogic) UpdateToken(req *types.TokenInfo) (*types.BaseMsgResp, error) {
	//isAdmin := l.ctx.Value("isAdmin").(bool)
	//if !isAdmin {
	//	l.Error("没有权限，请联系管理员", nil)
	//	return nil, errorx.NewDefaultError("没有权限，请联系管理员")
	//}
	var (
		expireAt *time.Time
		err      error
	)
	if req.ExpireAtStr != nil {
		expireAtdata, err := time.Parse("2006-01-02 15:04:05", *req.ExpireAtStr)
		if err != nil {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
		expireAt = &expireAtdata
	}

	if req.Token != nil {
		item, err := l.svcCtx.DB.Token.Query().Where(token.IDNEQ(*req.Id)).Where(token.TokenEQ(*req.Token)).First(l.ctx)
		if err != nil && !ent.IsNotFound(err) {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
		if item != nil && item.ID > 0 {
			return nil, errorx.NewCodeInvalidArgumentError("Token已经存在")
		}
	}
	err = l.svcCtx.DB.Token.UpdateOneID(*req.Id).
		SetNotNilExpireAt(expireAt).
		SetNotNilToken(req.Token).
		SetNotNilMAC(req.Mac).
		SetNotNilOrganizationID(req.OrganizationId).
		SetNotNilAgentID(req.AgentId).
		SetNotNilCustomAgentBase(req.CustomAgentBase).
		SetNotNilCustomAgentKey(req.CustomAgentKey).
		SetNotNilOpenaiBase(req.OpenaiBase).
		SetNotNilOpenaiKey(req.OpenaiKey).
		Exec(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	return &types.BaseMsgResp{Msg: errormsg.UpdateSuccess}, nil
}
