package admin_agent

import (
	"context"
	"fmt"

	"sim-server/app/main/api/internal/svc"
	"sim-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)
	}

	// 如果传入ProductId，添加筛选条件
	if req.ProductId != nil {
		builder = builder.Where("product_id = ?", *req.ProductId)
	}

	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[string]struct{})
	linkIdList := make([]string, 0, len(links))
	for _, link := range links {
		productIdSet[link.ProductId] = struct{}{}
		linkIdList = append(linkIdList, link.Id)
	}
	productIdList := make([]string, 0, len(productIdSet))
	for id := range productIdSet {
		productIdList = append(productIdList, id)
	}
	productNameMap := make(map[string]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
		}
	}

	// 批量查询短链信息
	shortLinkMap := make(map[string]string) // link_id -> short_link
	if len(linkIdList) > 0 {
		shortLinks, _ := l.svcCtx.AgentShortLinkModel.FindAll(l.ctx, l.svcCtx.AgentShortLinkModel.SelectBuilder().
			Where(squirrel.Eq{"link_id": linkIdList}).
			Where(squirrel.Eq{"type": 1}). // 推广报告类型
			Where(squirrel.Eq{"del_state": 0}), "")
		for _, sl := range shortLinks {
			if sl.LinkId.Valid && sl.ShortCode != "" && sl.PromotionDomain != "" {
				// 构建短链链接: {promotion_domain}/s/{shortCode}
				// promotion_domain 已经包含协议（http:// 或 https://）
				shortLinkMap[sl.LinkId.String] = fmt.Sprintf("%s/s/%s", sl.PromotionDomain, sl.ShortCode)
			}
		}
	}

	items := make([]types.AgentLinkListItem, 0, len(links))
	for _, link := range links {
		items = append(items, types.AgentLinkListItem{
			Id:          link.Id,
			AgentId:     link.AgentId,
			ProductId:   link.ProductId,
			ProductName: productNameMap[link.ProductId],
			SetPrice:    link.SetPrice,
			ShortLink:   shortLinkMap[link.Id], // 短链链接
			CreateTime:  link.CreateTime.Format("2006-01-02 15:04:05"),
		})
	}

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