package agent

import (
	"context"

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

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

func (l *GetAgentListLogic) GetAgentList(req *types.AgentListReq) (*types.AgentListResp, error) {
	orgId := l.ctx.Value("organizationId").(uint64)
	var predicates []predicate.Agent
	if req.OrganizationId != nil && *req.OrganizationId != 0 {
		isAdmin := l.ctx.Value("isAdmin").(bool)
		if isAdmin {
			predicates = append(predicates, agent.OrganizationIDEQ(*req.OrganizationId))
		} else {
			predicates = append(predicates, agent.OrganizationIDEQ(orgId))
		}
	} else {
		predicates = append(predicates, agent.OrganizationID(orgId))
	}
	if req.Name != nil {
		predicates = append(predicates, agent.NameContains(*req.Name))
	}
	if req.Role != nil {
		predicates = append(predicates, agent.RoleContains(*req.Role))
	}
	if req.Background != nil {
		predicates = append(predicates, agent.BackgroundContains(*req.Background))
	}
	if req.Status != nil {
		predicates = append(predicates, agent.Status(*req.Status))
	}
	data, err := l.svcCtx.DB.Agent.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
			types.AgentInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Name:         &v.Name,
				Role:         &v.Role,
				Status:       &v.Status,
				Background:   &v.Background,
				Examples:     &v.Examples,
				DatasetId:    &v.DatasetID,
				CollectionId: &v.CollectionID,
			})
	}

	return resp, nil
}
