package user

import (
	"context"
	"fmt"
	"time"

	"github.com/perfect-panel/server/internal/model/user"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/internal/types"
	"github.com/perfect-panel/server/pkg/constant"
	"github.com/perfect-panel/server/pkg/logger"
	"github.com/perfect-panel/server/pkg/loki"
	"github.com/perfect-panel/server/pkg/xerr"
	"github.com/pkg/errors"
)

type GetAgentRealtimeLogic struct {
	logger.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetAgentRealtimeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAgentRealtimeLogic {
	return &GetAgentRealtimeLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetAgentRealtimeLogic) GetAgentRealtime(req *types.GetAgentRealtimeRequest) (resp *types.GetAgentRealtimeResponse, err error) {
	// 1. Get current user
	u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
	if !ok {
		l.Errorw("[GetAgentRealtime] user not found in context")
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
	}

	now := time.Now()
	currentMonthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
	lastMonthStart := currentMonthStart.AddDate(0, -1, 0)

	var views, lastMonthViews int64
	var installs int64
	var paidCount int64

	// 2. 从 Loki 获取 views（nginx 访问日志）
	lokiCfg := l.svcCtx.Config.Loki
	if lokiCfg.Enable && lokiCfg.URL != "" && u.ReferCode != "" {
		lokiClient := loki.NewClient(lokiCfg.URL)
		lokiStats, err := lokiClient.GetInviteCodeMonthlyStats(l.ctx, u.ReferCode, now)
		if err != nil {
			l.Errorw("[GetAgentRealtime] Failed to fetch Loki stats",
				logger.Field("error", err.Error()),
				logger.Field("user_id", u.Id),
				logger.Field("refer_code", u.ReferCode))
			// 不返回错误，继续使用已有数据
		} else {
			views = lokiStats.MacClicks + lokiStats.WindowsClicks
			lastMonthViews = lokiStats.LastMonthMac + lokiStats.LastMonthWindows
			l.Infow("[GetAgentRealtime] Fetched Loki stats successfully",
				logger.Field("user_id", u.Id),
				logger.Field("refer_code", u.ReferCode),
				logger.Field("views", views),
				logger.Field("last_month_views", lastMonthViews))
		}
	}

	// 3. 从数据库获取安装量（被邀请注册用户数）
	err = l.svcCtx.DB.WithContext(l.ctx).
		Model(&user.User{}).
		Where("referer_id = ? AND created_at >= ? AND created_at < ?", u.Id, currentMonthStart, now).
		Count(&installs).Error
	if err != nil {
		l.Errorw("[GetAgentRealtime] Failed to count installs",
			logger.Field("error", err.Error()),
			logger.Field("user_id", u.Id))
		installs = 0
	}

	// 4. 获取付费用户数
	err = l.svcCtx.DB.WithContext(l.ctx).
		Table("`order`").
		Joins("LEFT JOIN user ON user.id = `order`.user_id").
		Where("user.referer_id = ? AND `order`.status IN ? AND `order`.updated_at >= ? AND `order`.updated_at < ?",
			u.Id, []int{2, 5}, currentMonthStart, now).
		Distinct("`order`.user_id").
		Count(&paidCount).Error
	if err != nil {
		l.Errorw("[GetAgentRealtime] Failed to count paid users",
			logger.Field("error", err.Error()),
			logger.Field("user_id", u.Id))
		paidCount = 0
	}

	// 5. 计算环比增长率
	growthRate := calculateGrowthRate([]int{int(lastMonthViews), int(views)})

	// 6. 计算付费用户环比增长率
	paidGrowthRate := l.calculatePaidGrowthRate(u.Id, currentMonthStart, lastMonthStart)

	return &types.GetAgentRealtimeResponse{
		Total:          views,
		Clicks:         views,
		Views:          views,
		Installs:       installs,
		PaidCount:      paidCount,
		GrowthRate:     growthRate,
		PaidGrowthRate: paidGrowthRate,
	}, nil
}

// calculatePaidGrowthRate 计算付费用户的环比增长率
func (l *GetAgentRealtimeLogic) calculatePaidGrowthRate(userId int64, currentMonthStart, lastMonthStart time.Time) string {
	db := l.svcCtx.DB

	// 查询本月付费用户数（本月有新订单的）
	var currentMonthCount int64
	err := db.Table("`order` o").
		Joins("JOIN user u ON o.user_id = u.id").
		Where("u.referer_id = ? AND o.status IN (?, ?) AND o.updated_at >= ?",
			userId, 2, 5, currentMonthStart).
		Distinct("o.user_id").
		Count(&currentMonthCount).Error

	if err != nil {
		l.Errorw("Failed to count current month paid users",
			logger.Field("error", err.Error()),
			logger.Field("user_id", userId))
		return "N/A"
	}

	// 查询上月付费用户数
	var lastMonthCount int64
	err = db.Table("`order` o").
		Joins("JOIN user u ON o.user_id = u.id").
		Where("u.referer_id = ? AND o.status IN (?, ?) AND o.updated_at >= ? AND o.updated_at < ?",
			userId, 2, 5, lastMonthStart, currentMonthStart).
		Distinct("o.user_id").
		Count(&lastMonthCount).Error

	if err != nil {
		l.Errorw("Failed to count last month paid users",
			logger.Field("error", err.Error()),
			logger.Field("user_id", userId))
		return "N/A"
	}

	// 计算增长率
	return calculateGrowthRate([]int{int(lastMonthCount), int(currentMonthCount)})
}

// calculateGrowthRate 计算环比增长率
// views: 月份数据数组，最后一个是本月，倒数第二个是上月
func calculateGrowthRate(views []int) string {
	if len(views) < 2 {
		return "N/A"
	}

	currentMonth := views[len(views)-1]
	lastMonth := views[len(views)-2]

	// 如果上月是0，无法计算百分比
	if lastMonth == 0 {
		if currentMonth == 0 {
			return "0%"
		}
		return "+100%"
	}

	// 计算增长率
	growth := float64(currentMonth-lastMonth) / float64(lastMonth) * 100

	// 格式化输出
	if growth > 0 {
		return fmt.Sprintf("+%.1f%%", growth)
	} else if growth < 0 {
		return fmt.Sprintf("%.1f%%", growth)
	}
	return "0%"
}
