package user

import (
	"context"
	"database/sql"

	"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 GetUserInviteStatsLogic struct {
	logger.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// Get user invite statistics
func NewGetUserInviteStatsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserInviteStatsLogic {
	return &GetUserInviteStatsLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetUserInviteStatsLogic) GetUserInviteStats(req *types.GetUserInviteStatsRequest) (resp *types.GetUserInviteStatsResponse, err error) {
	// 1. 从 context 中获取当前登录用户
	u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
	if !ok {
		l.Errorw("[GetUserInviteStats] user not found in context")
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
	}
	userId := u.Id

	// 2. 获取历史邀请佣金总额 (FriendlyCount): 从佣金日志中统计邀请人收到的佣金
	// type=33（佣金日志），object_id=userId，content JSON 中 type 为 331(购买) 或 332(续费) 时才是真实收入
	var totalCommission sql.NullInt64
	err = l.svcCtx.DB.WithContext(l.ctx).
		Table("system_logs").
		Select("COALESCE(SUM(JSON_EXTRACT(content, '$.amount')), 0) as total").
		Where("type = ? AND object_id = ? AND JSON_EXTRACT(content, '$.type') IN (?, ?)",
			33, userId, 331, 332).
		Scan(&totalCommission).Error

	if err != nil {
		l.Errorw("[GetUserInviteStats] sum commission failed",
			logger.Field("error", err.Error()),
			logger.Field("user_id", userId))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError),
			"sum commission failed: %v", err.Error())
	}

	friendlyCount := totalCommission.Int64

	// 3. 获取历史邀请总数 (HistoryCount)
	var historyCount int64
	err = l.svcCtx.DB.WithContext(l.ctx).
		Table("user").
		Where("referer_id = ?", userId).
		Count(&historyCount).Error
	if err != nil {
		l.Errorw("[GetUserInviteStats] count history users failed",
			logger.Field("error", err.Error()),
			logger.Field("user_id", userId))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError),
			"count history users failed: %v", err.Error())
	}

	return &types.GetUserInviteStatsResponse{
		FriendlyCount: friendlyCount,
		HistoryCount:  historyCount,
	}, nil
}
