package allocagent

import (
	"context"
	"wechat-api/ent/predicate"
	"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 GetAllocAgentListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *GetAllocAgentListLogic) GetAllocAgentList(req *types.AllocAgentListReq) (*types.AllocAgentListResp, error) {
	var predicates []predicate.AllocAgent
	data, err := l.svcCtx.DB.AllocAgent.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
			types.AllocAgentInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				UserId:         &v.UserID,
				OrganizationId: &v.OrganizationID,
				Agents:         v.Agents,
				Status:         &v.Status,
			})
	}

	return resp, nil
}
