package main

import (
	"math/rand"
	"testing"
)

func TestMachineryCheaperInIndustrialSystems(t *testing.T) {
	rng := rand.New(rand.NewSource(1))
	industrial := WayfarerSystem{Industrial: 1, Wealth: 0.5}
	agricultural := WayfarerSystem{Industrial: 0, Wealth: 0.5}

	machineryIdx := commodityIndexByKey(t, "commodity.machinery")
	industrialPrice := CommodityPrice(machineryIdx, industrial, rng)
	agriculturalPrice := CommodityPrice(machineryIdx, agricultural, rng)
	if industrialPrice >= agriculturalPrice {
		t.Errorf("машины должны быть дешевле в промышленной системе: industrial=%v agricultural=%v",
			industrialPrice, agriculturalPrice)
	}
}

func TestFoodCheaperInAgriculturalSystems(t *testing.T) {
	rng := rand.New(rand.NewSource(1))
	industrial := WayfarerSystem{Industrial: 1, Wealth: 0.5}
	agricultural := WayfarerSystem{Industrial: 0, Wealth: 0.5}

	foodIdx := commodityIndexByKey(t, "commodity.food")
	industrialPrice := CommodityPrice(foodIdx, industrial, rng)
	agriculturalPrice := CommodityPrice(foodIdx, agricultural, rng)
	if agriculturalPrice >= industrialPrice {
		t.Errorf("еда должна быть дешевле в аграрной системе: agricultural=%v industrial=%v",
			agriculturalPrice, industrialPrice)
	}
}

func TestLuxuriesCheaperInPoorSystems(t *testing.T) {
	rng := rand.New(rand.NewSource(1))
	rich := WayfarerSystem{Industrial: 0.5, Wealth: 1}
	poor := WayfarerSystem{Industrial: 0.5, Wealth: 0}

	luxuryIdx := commodityIndexByKey(t, "commodity.luxuries")
	richPrice := CommodityPrice(luxuryIdx, rich, rng)
	poorPrice := CommodityPrice(luxuryIdx, poor, rng)
	if poorPrice >= richPrice {
		t.Errorf("предметы роскоши должны быть дешевле в бедной системе при таком знаке WealthBias: poor=%v rich=%v",
			poorPrice, richPrice)
	}
}

func TestSellPriceLowerThanBuyPrice(t *testing.T) {
	buy := 100.0
	sell := SellPrice(buy)
	if sell >= buy {
		t.Errorf("цена продажи должна быть ниже цены покупки, получено sell=%v buy=%v", sell, buy)
	}
}

func TestCommodityPriceNeverNegativeOrZero(t *testing.T) {
	rng := rand.New(rand.NewSource(2))
	extreme := WayfarerSystem{Industrial: 1, Wealth: 1}
	for i := range WayfarerCommodities {
		for trial := 0; trial < 20; trial++ {
			p := CommodityPrice(i, extreme, rng)
			if p <= 0 {
				t.Fatalf("цена товара %d не должна быть <= 0, получено %v", i, p)
			}
		}
	}
}

func commodityIndexByKey(t *testing.T, key string) int {
	t.Helper()
	for i, c := range WayfarerCommodities {
		if c.Key == key {
			return i
		}
	}
	t.Fatalf("товар с ключом %q не найден", key)
	return -1
}
