package pickup

import (
	"encoding/json"
	"testing"

	"hfb_sys/backend/internal/model"

	"gorm.io/datatypes"
)

func TestBuildPickupPriceSnapshotSplitsOwnerPrice(t *testing.T) {
	raw, err := json.Marshal(map[string]any{
		"price_breakdown": map[string]any{
			"seller_coin_base_price": 233,
			"seller_total_price":     353,
			"platform_markup_amount": 30,
			"consumable_price":       120,
			"seller_ratio":           42.9,
			"buyer_ratio":            35.1,
		},
	})
	if err != nil {
		t.Fatalf("构造资产快照失败: %v", err)
	}

	snapshot := buildPickupPriceSnapshot(
		model.RentalListing{PriceCent: 38300},
		model.GameAccount{HafCoinAmount: 100000000, AssetSummary: datatypes.JSON(raw)},
	)

	assertInt64(t, "网站售价", snapshot.ListingPriceCent, 38300)
	assertInt64(t, "号主纯比价格", snapshot.OwnerPurePriceCent, 23300)
	assertInt64(t, "额外物品价格", snapshot.OwnerExtraItemPriceCent, 12000)
	assertInt64(t, "号主总价", snapshot.OwnerTotalPriceCent, 35300)
	assertInt64(t, "兼容号主价", snapshot.OwnerPriceCent, 35300)
	assertInt64(t, "网站加价", snapshot.WebsiteProfitCent, 3000)
	if snapshot.SellerRatio != 42.9 || snapshot.BuyerRatio != 35.1 {
		t.Fatalf("比例 = %.2f/%.2f, want 42.90/35.10", snapshot.SellerRatio, snapshot.BuyerRatio)
	}
}

func TestBuildPickupPriceSnapshotFallsBackToSplitSum(t *testing.T) {
	raw, err := json.Marshal(map[string]any{
		"price_breakdown": map[string]any{
			"seller_coin_base_price": 200,
			"consumable_price":       50,
		},
	})
	if err != nil {
		t.Fatalf("构造资产快照失败: %v", err)
	}

	snapshot := buildPickupPriceSnapshot(
		model.RentalListing{PriceCent: 30000},
		model.GameAccount{AssetSummary: datatypes.JSON(raw)},
	)

	assertInt64(t, "拆分合计总价", snapshot.OwnerTotalPriceCent, 25000)
	assertInt64(t, "纯比价格", snapshot.OwnerPurePriceCent, 20000)
	assertInt64(t, "额外物品价格", snapshot.OwnerExtraItemPriceCent, 5000)
	assertInt64(t, "网站加价兜底", snapshot.WebsiteProfitCent, 5000)
}

func assertInt64(t *testing.T, name string, got, want int64) {
	t.Helper()
	if got != want {
		t.Fatalf("%s = %d, want %d", name, got, want)
	}
}
