package financeorder

import (
	"testing"

	"hyapp-admin-server/internal/model"
	"hyapp-admin-server/internal/repository"

	"github.com/DATA-DOG/go-sqlmock"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func TestFinanceUSDTAddressesFromConfigsKeepsSupportedValidChainsInBusinessOrder(t *testing.T) {
	items, err := financeUSDTAddressesFromConfigs([]model.AppConfig{
		{Key: "BSC", Value: "0x55d398326f99059fF775485246999027B3197955", UpdatedAtMS: 200},
		{Key: "future-chain", Value: "not-exposed", UpdatedAtMS: 300},
		{Key: "TRON", Value: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", UpdatedAtMS: 100},
	})
	if err != nil {
		t.Fatalf("normalize USDT address configs failed: %v", err)
	}
	if len(items) != 2 || items[0].Chain != "TRON" || items[1].Chain != "BSC" {
		t.Fatalf("USDT addresses must expose only supported chains in business order: %+v", items)
	}
}

func TestFinanceUSDTAddressesFromConfigsRejectsMalformedStoredAddress(t *testing.T) {
	_, err := financeUSDTAddressesFromConfigs([]model.AppConfig{{Key: "TRON", Value: "wrong-app-address"}})
	if err == nil {
		t.Fatal("malformed SQL address must fail closed instead of being copied into a recharge order")
	}
}

func TestFinanceUSDTReceiveAddressMapsOffchainToCurrentTRONSQLRow(t *testing.T) {
	sqlDB, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("create sql mock failed: %v", err)
	}
	defer func() { _ = sqlDB.Close() }()
	gormDB, err := gorm.Open(mysql.New(mysql.Config{Conn: sqlDB, SkipInitializeWithVersion: true}), &gorm.Config{})
	if err != nil {
		t.Fatalf("create gorm db failed: %v", err)
	}
	const address = "TLv7wERsM42ZeobMrrKVC5C72d3gFUa44J"
	mock.ExpectQuery("SELECT \\* FROM `admin_app_configs` WHERE app_code = \\? AND `group` = \\? AND `key` = \\? AND is_deleted = FALSE").
		WithArgs("aslan", financeUSDTAddressGroup, "TRON", 1).
		WillReturnRows(sqlmock.NewRows([]string{"id", "app_code", "group", "key", "value", "description", "is_deleted", "created_at_ms", "updated_at_ms"}).
			AddRow(9, "aslan", financeUSDTAddressGroup, "TRON", address, "财务 USDT 收款地址", false, int64(100), int64(200)))

	service := NewService(repository.New(gormDB), nil, nil)
	got, err := service.financeUSDTReceiveAddress(" ASLAN ", "OFFCHAIN")
	if err != nil {
		t.Fatalf("load current Off-chain TRON address failed: %v", err)
	}
	if got != address {
		t.Fatalf("Off-chain must use current app-scoped TRON SQL address, got %q", got)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatalf("sql expectations mismatch: %v", err)
	}
}
