package commerce

import (
	"testing"
	"time"
)

func TestAutoRenewalEventKeyUsesOriginalExpiryInUTC(t *testing.T) {
	expires := time.Date(2026, 7, 10, 8, 9, 10, 0, time.FixedZone("UTC+8", 8*60*60))
	if got, want := autoRenewalEventKey(42, expires, 2), "auto_renew:42:20260710000910:2"; got != want {
		t.Fatalf("autoRenewalEventKey() = %q, want %q", got, want)
	}
}

func TestCompensatablePaidOrderSnapshot(t *testing.T) {
	advanced := Order{ID: 1, ItemsSnapshot: jsonRawFromAny([]map[string]any{{
		"type": "disk_addon",
		"detail": map[string]any{"quote": map[string]any{
			"instance_id":      7,
			"recurring_amount": 500,
		}},
	}})}
	kind, snapshot, err := compensatablePaidOrderSnapshot(advanced)
	if err != nil {
		t.Fatal(err)
	}
	if kind != "disk_addon" || intValueAny(snapshot["recurring_amount"], 0) != 500 {
		t.Fatalf("advanced snapshot = %q %#v", kind, snapshot)
	}

	renewal := Order{ID: 2, ItemsSnapshot: jsonRawFromAny([]map[string]any{{
		"type":                  "renewal",
		"instance_id":           8,
		"old_expires_at":        "2026-07-10T00:00:00Z",
		"old_next_renew_amount": 1200,
	}})}
	kind, snapshot, err = compensatablePaidOrderSnapshot(renewal)
	if err != nil {
		t.Fatal(err)
	}
	if kind != "renewal" || intValueAny(snapshot["instance_id"], 0) != 8 {
		t.Fatalf("renewal snapshot = %q %#v", kind, snapshot)
	}
}

func TestCompensatablePaidActionTypes(t *testing.T) {
	for _, action := range []string{"upgrade", "disk_create", "disk_resize", "instance_renew"} {
		if !isCompensatablePaidActionType(action) {
			t.Fatalf("%q should be compensatable", action)
		}
	}
	for _, action := range []string{"power-on", "instance_delete", "disk_mount"} {
		if isCompensatablePaidActionType(action) {
			t.Fatalf("%q should not be compensatable", action)
		}
	}
}

func TestCheckoutInstanceStateTracksStockAndPaidAmount(t *testing.T) {
	payload := jsonMap(checkoutInstanceState(Product{ID: 7, StockPolicy: "tracked"}, 321))
	stock, _ := payload[checkoutStockMarker].(map[string]any)
	billing, _ := payload["local_billing"].(map[string]any)
	if !truthyAny(stock["decremented"]) || intValueAny(stock["product_id"], 0) != 7 {
		t.Fatalf("stock state = %#v", stock)
	}
	if intValueAny(billing["paid_amount_cents"], 0) != 321 {
		t.Fatalf("billing state = %#v", billing)
	}
}
