package user

import (
	"context"
	"database/sql"

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

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

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

func (l *GetAdminUserInviteStatsLogic) GetAdminUserInviteStats(req *types.GetAdminUserInviteStatsRequest) (resp *types.GetAdminUserInviteStatsResponse, err error) {
	userId := req.UserId

	// 邀请总人数
	var inviteCount int64
	if err = l.svcCtx.DB.WithContext(l.ctx).
		Table("user").
		Where("referer_id = ? AND deleted_at IS NULL", userId).
		Count(&inviteCount).Error; err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count invite users failed: %v", err)
	}

	// 历史累计佣金（来自 system_logs type=33 的佣金记录）
	var totalCommission sql.NullInt64
	if 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; err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "sum commission failed: %v", err)
	}

	// 当前佣金余额
	type UserCommission struct {
		Commission         int64 `gorm:"column:commission"`
		ReferralPercentage uint8 `gorm:"column:referral_percentage"`
		OnlyFirstPurchase  bool  `gorm:"column:only_first_purchase"`
	}
	var userInfo UserCommission
	if err = l.svcCtx.DB.WithContext(l.ctx).
		Table("user").
		Select("commission, referral_percentage, only_first_purchase").
		Where("id = ?", userId).
		Scan(&userInfo).Error; err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get user commission failed: %v", err)
	}

	return &types.GetAdminUserInviteStatsResponse{
		InviteCount:        inviteCount,
		TotalCommission:    totalCommission.Int64,
		CurrentCommission:  userInfo.Commission,
		ReferralPercentage: userInfo.ReferralPercentage,
		OnlyFirstPurchase:  userInfo.OnlyFirstPurchase,
	}, nil
}
