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 CreateTokenLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *CreateTokenLogic) CreateToken(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
	)
	expireAt, err = time.Parse("2006-01-02 15:04:05", *req.ExpireAtStr)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	item, err := l.svcCtx.DB.Token.Query().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.Create().
		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).
		Save(l.ctx)

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

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