//go:build ignore

package handler

import (
	"net/http"
	"strconv"
	"time"
	"xboard-go/internal/database"
	"xboard-go/internal/model"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func NodeUser(c *gin.Context) {
	nodePtr, _ := c.Get("node")
	_ = nodePtr.(*model.Server) // Silence unused node for now

	var users []model.User
	// Basic filtering: banned=0 and not expired
	query := database.DB.Model(&model.User{}).
		Where("banned = ? AND (expired_at IS NULL OR expired_at > ?)", 0, time.Now().Unix())

	if err := query.Find(&users).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "获取用户失败"})
		return
	}

	type UniUser struct {
		ID   int    `json:"id"`
		UUID string `json:"uuid"`
	}

	uniUsers := make([]UniUser, len(users))
	for i, u := range users {
		uniUsers[i] = UniUser{ID: u.ID, UUID: u.UUID}
	}

	c.JSON(http.StatusOK, gin.H{
		"users": uniUsers,
	})
}

func NodePush(c *gin.Context) {
	nodePtr, _ := c.Get("node")
	node := nodePtr.(*model.Server)

	var data map[string][]int64
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "参数错误"})
		return
	}

	for userIDStr, traffic := range data {
		userID, err := strconv.Atoi(userIDStr)
		if err != nil {
			continue
		}
		if len(traffic) < 2 {
			continue
		}
		u := traffic[0]
		d := traffic[1]

		// Update user traffic
		database.DB.Model(&model.User{}).Where("id = ?", userID).
			Updates(map[string]interface{}{
				"u": gorm.Expr("u + ?", u),
				"d": gorm.Expr("d + ?", d),
				"t": time.Now().Unix(),
			})

		// Update node traffic
		database.DB.Model(&model.Server{}).Where("id = ?", node.ID).
			Updates(map[string]interface{}{
				"u": gorm.Expr("u + ?", u),
				"d": gorm.Expr("d + ?", d),
			})
	}

	c.JSON(http.StatusOK, gin.H{"data": true})
}

// Config, Alive, Status handlers suppressed for brevity in this step
