package admin_agent

import (
	"context"
	"fmt"
	"time"

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

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

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

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

func (l *AdminGetAgentStatisticsLogic) AdminGetAgentStatistics(req *types.AdminGetAgentStatisticsReq) (resp *types.AdminGetAgentStatisticsResp, err error) {
	// 使用AgentModel的SelectBuilder和FindCount方法获取总代理数
	totalBuilder := l.svcCtx.AgentModel.SelectBuilder()
	totalAgentCount, err := l.svcCtx.AgentModel.FindCount(l.ctx, totalBuilder, "id")
	if err != nil {
		logx.Errorf("获取总代理数失败: %v", err)
		return nil, fmt.Errorf("获取总代理数失败: %w", err)
	}

	// 获取今日新增代理数
	todayBuilder := l.svcCtx.AgentModel.SelectBuilder()
	today := time.Now()
	startOfDay := time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, today.Location())
	endOfDay := startOfDay.Add(24 * time.Hour)
	todayBuilder = todayBuilder.Where("create_time >= ? AND create_time < ?", startOfDay, endOfDay)

	todayAgentCount, err := l.svcCtx.AgentModel.FindCount(l.ctx, todayBuilder, "id")
	if err != nil {
		logx.Errorf("获取今日新增代理数失败: %v", err)
		return nil, fmt.Errorf("获取今日新增代理数失败: %w", err)
	}

	resp = &types.AdminGetAgentStatisticsResp{
		TotalAgentCount: totalAgentCount,
		TodayAgentCount: todayAgentCount,
	}

	return resp, nil
}
