package admin_agent

import (
	"context"
	"time"

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

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

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

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

func (l *AdminGetStatisticsOverviewLogic) AdminGetStatisticsOverview() (resp *types.AdminGetStatisticsOverviewResp, err error) {
	// Get current time for date filtering
	now := time.Now()
	todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())

	// 1. Total agents - count from agent table
	totalAgents, err := l.svcCtx.AgentModel.FindCount(l.ctx, l.svcCtx.AgentModel.SelectBuilder(), "id")
	if err != nil {
		l.Errorf("Failed to count total agents: %v", err)
		return nil, err
	}

	// 2. Today new agents - count agents created today
	todayAgentsBuilder := l.svcCtx.AgentModel.SelectBuilder().Where(squirrel.GtOrEq{"create_time": todayStart})
	todayNewAgents, err := l.svcCtx.AgentModel.FindCount(l.ctx, todayAgentsBuilder, "id")
	if err != nil {
		l.Errorf("Failed to count today new agents: %v", err)
		return nil, err
	}

	// 3. Total orders - count from agent_order table
	totalOrders, err := l.svcCtx.AgentOrderModel.FindCount(l.ctx, l.svcCtx.AgentOrderModel.SelectBuilder(), "id")
	if err != nil {
		l.Errorf("Failed to count total orders: %v", err)
		return nil, err
	}

	// 4. Today orders - count orders created today
	todayOrdersBuilder := l.svcCtx.AgentOrderModel.SelectBuilder().Where(squirrel.GtOrEq{"create_time": todayStart})
	todayOrders, err := l.svcCtx.AgentOrderModel.FindCount(l.ctx, todayOrdersBuilder, "id")
	if err != nil {
		l.Errorf("Failed to count today orders: %v", err)
		return nil, err
	}

	// 5. Total order amount - sum from agent_order table
	totalOrderAmount, err := l.svcCtx.AgentOrderModel.FindSum(l.ctx, l.svcCtx.AgentOrderModel.SelectBuilder(), "order_amount")
	if err != nil {
		l.Errorf("Failed to sum total order amount: %v", err)
		return nil, err
	}

	// 6. Today order amount - sum orders created today
	todayOrderAmount, err := l.svcCtx.AgentOrderModel.FindSum(l.ctx, todayOrdersBuilder, "order_amount")
	if err != nil {
		l.Errorf("Failed to sum today order amount: %v", err)
		return nil, err
	}

	// 7. Total commission - sum of all commission amounts
	totalCommission, err := l.svcCtx.AgentCommissionModel.FindSum(l.ctx, l.svcCtx.AgentCommissionModel.SelectBuilder(), "amount")
	if err != nil {
		l.Errorf("Failed to sum total commission: %v", err)
		return nil, err
	}

	// 8. Today commission - sum of today's commission
	todayCommissionBuilder := l.svcCtx.AgentCommissionModel.SelectBuilder().Where(squirrel.GtOrEq{"create_time": todayStart})
	todayCommission, err := l.svcCtx.AgentCommissionModel.FindSum(l.ctx, todayCommissionBuilder, "amount")
	if err != nil {
		l.Errorf("Failed to sum today commission: %v", err)
		return nil, err
	}

	// 9. Pending withdraw - sum of withdraw records with status=0
	pendingWithdrawBuilder := l.svcCtx.AgentWithdrawModel.SelectBuilder().Where(squirrel.Eq{"status": 0})
	pendingWithdraw, err := l.svcCtx.AgentWithdrawModel.FindSum(l.ctx, pendingWithdrawBuilder, "withdraw_amount")
	if err != nil {
		l.Errorf("Failed to sum pending withdraw: %v", err)
		return nil, err
	}

	// 10. Month order amount - sum of orders in current month
	monthOrderAmountBuilder := l.svcCtx.AgentOrderModel.SelectBuilder().Where(squirrel.GtOrEq{"create_time": monthStart})
	monthOrderAmount, err := l.svcCtx.AgentOrderModel.FindSum(l.ctx, monthOrderAmountBuilder, "order_amount")
	if err != nil {
		l.Errorf("Failed to sum month order amount: %v", err)
		return nil, err
	}

	// 11. Month commission - sum of commission in current month
	monthCommissionBuilder := l.svcCtx.AgentCommissionModel.SelectBuilder().Where(squirrel.GtOrEq{"create_time": monthStart})
	monthCommission, err := l.svcCtx.AgentCommissionModel.FindSum(l.ctx, monthCommissionBuilder, "amount")
	if err != nil {
		l.Errorf("Failed to sum month commission: %v", err)
		return nil, err
	}

	resp = &types.AdminGetStatisticsOverviewResp{
		TotalAgents:      totalAgents,
		TodayNewAgents:   todayNewAgents,
		TotalOrders:      totalOrders,
		TodayOrders:      todayOrders,
		TotalOrderAmount: totalOrderAmount,
		TodayOrderAmount: todayOrderAmount,
		TotalCommission:  totalCommission,
		TodayCommission:  todayCommission,
		PendingWithdraw:  pendingWithdraw,
		MonthOrderAmount: monthOrderAmount,
		MonthCommission:  monthCommission,
	}

	return resp, nil
}
