package user

import (
	"context"

	"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/xerr"
	"github.com/pkg/errors"
)

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

// NewGetAgentDownloadsLogic 创建 GetAgentDownloadsLogic 实例
func NewGetAgentDownloadsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAgentDownloadsLogic {
	return &GetAgentDownloadsLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// PlatformStats 各平台设备统计结果
type PlatformStats struct {
	Android int64 `gorm:"column:android"`
	IOS     int64 `gorm:"column:ios"`
	Mac     int64 `gorm:"column:mac"`
	Windows int64 `gorm:"column:windows"`
	Total   int64 `gorm:"column:total"`
}

// GetAgentDownloads 获取用户代理下载统计数据
// 基于用户邀请码查询被邀请用户的设备UA来统计各平台安装量
func (l *GetAgentDownloadsLogic) GetAgentDownloads(req *types.GetAgentDownloadsRequest) (resp *types.GetAgentDownloadsResponse, err error) {
	// 1. 从 context 获取用户信息
	u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
	if !ok {
		l.Errorw("[GetAgentDownloads] user not found in context")
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
	}

	// 2. 通过数据库查询各平台设备安装量
	// 基于 user_device 表的 user_agent 字段判断平台
	// UA格式: HiVPN/1.0.0 (平台; 设备; 版本) Flutter
	var stats PlatformStats
	err = l.svcCtx.DB.WithContext(l.ctx).
		Table("user u").
		Select(`
			SUM(CASE WHEN d.user_agent LIKE '%(Android;%' THEN 1 ELSE 0 END) AS android,
			SUM(CASE WHEN d.user_agent LIKE '%(iOS;%' THEN 1 ELSE 0 END) AS ios,
			SUM(CASE WHEN d.user_agent LIKE '%(macOS;%' THEN 1 ELSE 0 END) AS mac,
			SUM(CASE WHEN d.user_agent LIKE '%(Windows;%' THEN 1 ELSE 0 END) AS windows,
			COUNT(*) AS total
		`).
		Joins("JOIN user_device d ON u.id = d.user_id").
		Where("u.referer_id = ?", u.Id).
		Scan(&stats).Error

	if err != nil {
		l.Errorw("[GetAgentDownloads] query platform stats failed",
			logger.Field("error", err.Error()),
			logger.Field("user_id", u.Id))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError),
			"query platform stats failed: %v", err.Error())
	}

	l.Infow("[GetAgentDownloads] platform stats fetched successfully",
		logger.Field("user_id", u.Id),
		logger.Field("refer_code", u.ReferCode),
		logger.Field("android", stats.Android),
		logger.Field("ios", stats.IOS),
		logger.Field("mac", stats.Mac),
		logger.Field("windows", stats.Windows),
		logger.Field("total", stats.Total))

	// 3. 构造响应
	return &types.GetAgentDownloadsResponse{
		Total: stats.Total,
		Platforms: types.PlatformDownloads{
			IOS:     stats.IOS,
			Android: stats.Android,
			Windows: stats.Windows,
			Mac:     stats.Mac,
		},
		ComparisonRate: "", // 不再计算环比
	}, nil
}
