package salestargets

import (
	"testing"

	"github.com/shopspring/decimal"
)

func TestSalesTarget_AchievementPct(t *testing.T) {
	target := SalesTarget{
		TargetAmount:   decimal.NewFromInt(10000000), // Rp 10.000.000
		AchievedAmount: decimal.NewFromInt(72187789), // Rp 72.187.789
	}

	pct, _ := target.AchievedAmount.Div(target.TargetAmount).Mul(decimal.NewFromInt(100)).Round(1).Float64()
	if pct != 721.9 {
		t.Fatalf("expected 721.9%%, got %f", pct)
	}

	// Tiny achievement like Rp 99 out of Rp 15.000.000 should round cleanly to 0.0
	smallTarget := SalesTarget{
		TargetAmount:   decimal.NewFromInt(15000000),
		AchievedAmount: decimal.NewFromFloat(98.98),
	}
	smallPct, _ := smallTarget.AchievedAmount.Div(smallTarget.TargetAmount).Mul(decimal.NewFromInt(100)).Round(1).Float64()
	if smallPct != 0.0 {
		t.Fatalf("expected 0.0%% for tiny ratio, got %f", smallPct)
	}
}

func TestSalesTarget_ZeroTargetAmountHandled(t *testing.T) {
	target := SalesTarget{
		TargetAmount:   decimal.Zero,
		AchievedAmount: decimal.NewFromInt(500000),
	}

	var pct float64
	if target.TargetAmount.Sign() > 0 {
		pct, _ = target.AchievedAmount.Div(target.TargetAmount).Mul(decimal.NewFromInt(100)).Float64()
	}
	if pct != 0 {
		t.Fatalf("expected 0%% for zero target amount, got %f", pct)
	}
}

func TestValidateScope_HierarchyPairs(t *testing.T) {
	tests := []struct {
		role  string
		scope string
		want  bool
	}{
		{"gm", "kota", true},
		{"bm", "kecamatan", true},
		{"spv", "kelurahan", true},
		{"sales", "desa", true},
		{"gm", "desa", false},
		{"sales", "kota", false},
		{"unknown", "kota", false},
	}

	for _, tt := range tests {
		if got := validateScope(tt.role, tt.scope); got != tt.want {
			t.Errorf("validateScope(%q, %q) = %v; want %v", tt.role, tt.scope, got, tt.want)
		}
	}
}
