package admin_agent

import (
	"context"
	"fmt"

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

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

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

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

func (l *AdminGetAgentLinkProductStatisticsLogic) AdminGetAgentLinkProductStatistics(req *types.AdminGetAgentLinkProductStatisticsReq) (resp *types.AdminGetAgentLinkProductStatisticsResp, err error) {
	// 构建查询
	query := squirrel.Select(
		"p.product_name",
		"COUNT(al.id) as link_count",
	).
		From("agent_link al").
		Join("product p ON al.product_id = p.id").
		Where(squirrel.Eq{"al.del_state": 0}).
		Where(squirrel.Eq{"p.del_state": 0}).
		GroupBy("p.product_name").
		OrderBy("link_count DESC")

	// 执行查询
	sql, args, err := query.ToSql()
	if err != nil {
		return nil, err
	}

	type Result struct {
		ProductName string `db:"product_name"`
		LinkCount   int64  `db:"link_count"`
	}

	var results []Result
	// 使用模型的方法执行查询
	// 通过反射获取底层的QueryRowsNoCacheCtx方法，避免直接类型断言
	if agentLinkModel, ok := l.svcCtx.AgentLinkModel.(interface {
		QueryRowsNoCacheCtx(ctx context.Context, v interface{}, query string, args ...interface{}) error
	}); ok {
		err = agentLinkModel.QueryRowsNoCacheCtx(l.ctx, &results, sql, args...)
	} else {
		// 如果无法使用模型的方法，则使用原始的连接方式（安全地获取连接）
		if cachedConn, ok := l.svcCtx.AgentLinkModel.(interface {
			GetConn() interface{}
		}); ok {
			conn := cachedConn.GetConn()
			if sqlxConn, ok := conn.(interface {
				QueryRowsCtx(ctx context.Context, v interface{}, query string, args ...interface{}) error
			}); ok {
				err = sqlxConn.QueryRowsCtx(l.ctx, &results, sql, args...)
			} else {
				return nil, fmt.Errorf("无法获取数据库连接")
			}
		} else {
			return nil, fmt.Errorf("无法获取数据库连接")
		}
	}

	if err != nil {
		return nil, err
	}

	// 处理空结果
	if len(results) == 0 {
		return &types.AdminGetAgentLinkProductStatisticsResp{
			Items: []types.AgentLinkProductStatisticsItem{},
		}, nil
	}

	// 转换为返回结果
	items := make([]types.AgentLinkProductStatisticsItem, 0, len(results))
	for _, r := range results {
		items = append(items, types.AgentLinkProductStatisticsItem{
			ProductName: r.ProductName,
			LinkCount:   r.LinkCount,
		})
	}

	return &types.AdminGetAgentLinkProductStatisticsResp{
		Items: items,
	}, nil
}
