package main

import (
	"bindbox-game/internal/repository/mysql"
	"bindbox-game/internal/repository/mysql/model"
	"fmt"
	"log"
)

func main() {
	// Initialize DB (Implicitly loads configs via init())
	db, err := mysql.New()
	if err != nil {
		log.Fatalf("failed to init db: %v", err)
	}

	// 1. Get all users
	var userIDs []int64
	if err := db.GetDbR().Model(&model.Users{}).Pluck("id", &userIDs).Error; err != nil {
		log.Fatalf("failed to get users: %v", err)
	}

	fmt.Printf("Checking points integrity for %d users...\n", len(userIDs))
	fmt.Println("UserID | LedgerSum | BalanceSum | Diff")
	fmt.Println("-------|-----------|------------|------")

	errorCount := 0

	for _, uid := range userIDs {
		// Sum Ledger
		var ledgerSum int64
		if err := db.GetDbR().Model(&model.UserPointsLedger{}).
			Where("user_id = ?", uid).
			Select("COALESCE(SUM(points), 0)").
			Scan(&ledgerSum).Error; err != nil {
			log.Printf("failed to sum ledger for user %d: %v", uid, err)
			continue
		}

		// Sum Balance
		var balanceSum int64
		if err := db.GetDbR().Model(&model.UserPoints{}).
			Where("user_id = ?", uid).
			Select("COALESCE(SUM(points), 0)").
			Scan(&balanceSum).Error; err != nil {
			log.Printf("failed to sum balance for user %d: %v", uid, err)
			continue
		}

		diff := ledgerSum - balanceSum
		if diff != 0 || uid == 9018 {
			errorCount++
			fmt.Printf("%6d | %9d | %10d | %4d\n", uid, ledgerSum, balanceSum, diff)
			// Show ledgers for 9018
			if uid == 9018 {
				var ledgers []model.UserPointsLedger
				db.GetDbR().Where("user_id = ?", uid).Find(&ledgers)
				for _, l := range ledgers {
					fmt.Printf("  -> Ledger ID: %d, Action: %s, Points: %d\n", l.ID, l.Action, l.Points)
				}
			}
		}
	}

	if errorCount == 0 {
		fmt.Println("\nAll users verified. No discrepancies found.")
	} else {
		fmt.Printf("\nFound %d users with point discrepancies.\n", errorCount)
	}
}
