package UsageDetail

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent/usagedetail"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

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

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

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

func (l *GetUsageDetailLogic) GetUsageDetail(req *types.IDReq) (resp *types.UsageDetailResp, err error) {
	if req.Id <= 0 {
		return nil, errorx.NewInvalidArgumentError("参数错误")
	}

	data, err := l.svcCtx.DB.UsageDetail.Query().Where(usagedetail.ID(req.Id)).Only(l.ctx)

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

	resp = &types.UsageDetailResp{}
	resp.Msg = errormsg.Success

	if data != nil {
		app := "未知"
		if data.App == 1 {
			app = "智能回复"
		} else if data.App == 2 {
			app = "AI角色-优化问题"
		} else if data.App == 3 {
			app = "AI角色-回复"
		} else if data.App == 4 {
			app = "SOP-节点判断"
		} else if data.App == 5 {
			app = "SOP-节点判断"
		}
		request := data.Request
		if data.App == 2 {
			request = "问题优化"
		} else if data.App == 4 {
			request = "节点判断"
		}
		resp.Data = types.UsageDetailInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			Status:           &data.Status,
			Type:             &data.Type,
			BotId:            &data.BotID,
			ReceiverId:       &data.ReceiverID,
			App:              &app,
			SessionId:        &data.SessionID,
			Request:          &request,
			Response:         &data.Response,
			TotalTokens:      &data.TotalTokens,
			PromptTokens:     &data.PromptTokens,
			CompletionTokens: &data.CompletionTokens,
			OrganizationId:   &data.OrganizationID,
		}
	}

	return resp, nil
}
