package credit_balance

import (
	"context"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"

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

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

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

func (l *GetCreditBalanceByIdLogic) GetCreditBalanceById(req *types.IDReq) (*types.CreditBalanceInfoResp, error) {
	data, err := l.svcCtx.DB.CreditBalance.Get(l.ctx, req.Id)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	departmentInfo, err := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: data.OrganizationID})
	if err != nil {
		return nil, err
	}
	return &types.CreditBalanceInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.CreditBalanceInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			UserId:           &data.UserID,
			Balance:          &data.Balance,
			OrganizationId:   &data.OrganizationID,
			OrganizationName: departmentInfo.Name,
		},
	}, nil
}
