package admin_agent

import (
	"context"

	"znc-server/app/main/api/internal/svc"
	"znc-server/app/main/api/internal/types"

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

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

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

func (l *AdminGetAgentLinkListLogic) AdminGetAgentLinkList(req *types.AdminGetAgentLinkListReq) (resp *types.AdminGetAgentLinkListResp, err error) {
	builder := l.svcCtx.AgentLinkModel.SelectBuilder()
	if req.AgentId != nil {
		builder = builder.Where("agent_id = ?", *req.AgentId)
	}
	if req.LinkIdentifier != nil && *req.LinkIdentifier != "" {
		builder = builder.Where("link_identifier = ?", *req.LinkIdentifier)
	}

	// 先查出所有product_id对应的product_name（如有product_name筛选，需反查id）
	var productIdFilter int64
	if req.ProductName != nil && *req.ProductName != "" {
		// 只支持精确匹配，如需模糊可扩展
		products, err := l.svcCtx.ProductModel.FindAll(l.ctx, l.svcCtx.ProductModel.SelectBuilder().Where(squirrel.Eq{"product_name": *req.ProductName}), "")
		if err != nil || len(products) == 0 {
			return &types.AdminGetAgentLinkListResp{Total: 0, Items: []types.AgentLinkListItem{}}, nil
		}
		productIdFilter = products[0].Id
		builder = builder.Where("product_id = ?", productIdFilter)
	}

	links, total, err := l.svcCtx.AgentLinkModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "id DESC")
	if err != nil {
		return nil, err
	}

	// 批量查product_id->name，避免N+1
	productIdSet := make(map[int64]struct{})
	for _, link := range links {
		productIdSet[link.ProductId] = struct{}{}
	}
	productIdList := make([]int64, 0, len(productIdSet))
	for id := range productIdSet {
		productIdList = append(productIdList, id)
	}
	productNameMap := make(map[int64]string)
	if len(productIdList) > 0 {
		products, _ := l.svcCtx.ProductModel.FindAll(l.ctx, l.svcCtx.ProductModel.SelectBuilder().Where(squirrel.Eq{"id": productIdList}), "")
		for _, p := range products {
			productNameMap[p.Id] = p.ProductName
		}
	}

	items := make([]types.AgentLinkListItem, 0, len(links))
	for _, link := range links {
		items = append(items, types.AgentLinkListItem{
			AgentId:        link.AgentId,
			ProductName:    productNameMap[link.ProductId],
			Price:          link.Price,
			LinkIdentifier: link.LinkIdentifier,
			CreateTime:     link.CreateTime.Format("2006-01-02 15:04:05"),
		})
	}

	resp = &types.AdminGetAgentLinkListResp{
		Total: total,
		Items: items,
	}
	return
}
