package allocagent

import (
	"context"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"wechat-api/ent"
	"wechat-api/ent/allocagent"
	"wechat-api/ent/predicate"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

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

func (l *QueryAllocAgentLogic) QueryAllocAgent(req *types.AllocAgentQuery) (*types.AllocAgentInfoResp, error) {
	resp := types.AllocAgentInfoResp{}

	var predicates []predicate.AllocAgent
	if req.UserId != nil && *req.UserId != "" {
		predicates = append(predicates, allocagent.UserIDEQ(*req.UserId))
	}
	if req.OrganizationId != nil && *req.OrganizationId > 0 {
		predicates = append(predicates, allocagent.OrganizationIDEQ(*req.OrganizationId))
	}

	item, err := l.svcCtx.DB.AllocAgent.Query().Where(predicates...).First(l.ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return &resp, nil
		}
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	resp.Data = types.AllocAgentInfo{
		BaseIDInfo: types.BaseIDInfo{
			Id:        &item.ID,
			CreatedAt: pointy.GetPointer(item.CreatedAt.UnixMilli()),
			UpdatedAt: pointy.GetPointer(item.UpdatedAt.UnixMilli()),
		},
		UserId:         &item.UserID,
		OrganizationId: &item.OrganizationID,
		Agents:         item.Agents,
		Status:         &item.Status,
	}

	return &resp, nil
}
