package xunji

import (
	"context"

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

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

func (l *CreateXunjiLogic) CreateXunji(req *types.XunjiInfo) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	_, err := l.svcCtx.DB.Xunji.Create().
		SetStatus(1).
		SetNotNilAppKey(req.AppKey).
		SetNotNilAppSecret(req.AppSecret).
		SetNotNilToken(req.Token).
		SetNotNilEncodingKey(req.EncodingKey).
		SetNotNilAgentID(req.AgentId).
		SetOrganizationID(organizationId).
		SetNotNilWxid(req.Wxid).
		SetNotNilAPIBase(req.ApiBase).
		SetNotNilAPIKey(req.ApiKey).
		Save(l.ctx)

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

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