package UsageTotal

import (
	"context"
	"fmt"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"wechat-api/ent/predicate"
	"wechat-api/ent/usagetotal"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *GetUsageTotalListLogic) GetUsageTotalList(req *types.UsageTotalListReq) (resp *types.UsageTotalListResp, err error) {
	isAdmin := l.ctx.Value("isAdmin").(bool)

	if !isAdmin {
		return nil, fmt.Errorf("GetUsageTotalList failed")
	}
	var predicates []predicate.UsageTotal
	predicates = append(predicates, usagetotal.OrganizationIDEQ(*req.OrganizationId))

	data, err := l.svcCtx.DB.UsageTotal.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

	resp = &types.UsageTotalListResp{}
	resp.Msg = errormsg.Success
	resp.Data.Total = data.PageDetails.Total

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
			types.UsageTotalInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Status:         &v.Status,
				Type:           &v.Type,
				BotId:          &v.BotID,
				TotalTokens:    &v.TotalTokens,
				StartIndex:     &v.StartIndex,
				EndIndex:       &v.EndIndex,
				OrganizationId: &v.OrganizationID,
			})
	}

	return resp, nil
	//return nil, nil
}
