package credit_balance

import (
	"context"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"github.com/zeromicro/go-zero/core/errorx"

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

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

func (l *CreateCreditBalanceLogic) CreateCreditBalance(req *types.CreditBalanceInfo) (*types.BaseMsgResp, error) {
	_, err := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: *req.OrganizationId})
	if err != nil {
		return nil, errorx.NewAlreadyExistsError("租户不存在")
	}

	_, err = l.svcCtx.DB.CreditBalance.Create().
		SetNotNilUserID(req.UserId).
		SetNotNilBalance(req.Balance).
		SetNotNilStatus(tea.Int(1)).
		SetNotNilOrganizationID(req.OrganizationId).
		Save(l.ctx)

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

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