package main

import (
	"os"
	"strings"
	"testing"
)

// The build gate is only as good as the moments it runs at.
//
// It used to run at startup alone, on the profile active then — and a fresh
// install has NO callsign at that point. The operator typed theirs afterwards,
// so a denied call ran for the whole session and reached the telemetry, which
// reads the very same field. Every place that can make a denied callsign the
// ACTIVE one has to re-ask.
func TestCallGateRunsWhereverTheActiveCallsignChanges(t *testing.T) {
	src, err := os.ReadFile("app.go")
	if err != nil {
		t.Fatal(err)
	}
	for _, fn := range []string{
		"func (a *App) startup(ctx context.Context) {",                 // launch
		"func (a *App) SaveStationSettings(s StationSettings) error {", // the call is entered here
		"func (a *App) SaveProfile(p profile.Profile) (profile.Profile, error) {",
		"func (a *App) ActivateProfile(id int64) error {",
	} {
		body := funcBody(t, string(src), fn)
		if !strings.Contains(body, "enforceCallGate(") {
			t.Errorf("%s can change the active callsign but never re-checks the gate", fn)
		}
	}
}

// The hashes are the whole mechanism: a truncated or re-cased entry silently
// matches nothing, and nothing in the running program would ever say so.
func TestDeniedCallHashesAreWellFormed(t *testing.T) {
	if len(deniedCallHashes) == 0 {
		t.Fatal("the deny list is empty — the gate has stopped gating")
	}
	for h := range deniedCallHashes {
		if len(h) != 64 {
			t.Errorf("hash %q is %d chars, want 64", h, len(h))
		}
		if h != strings.ToLower(h) {
			t.Errorf("hash %q is not lower-case, so it can never match", h)
		}
	}
}

// A slashed call must reduce to the real one, or /P is a way round the gate.
func TestDenyBaseCall(t *testing.T) {
	for in, want := range map[string]string{
		"f4xyz":    "F4XYZ",
		" F4XYZ ":  "F4XYZ",
		"F4XYZ/P":  "F4XYZ",
		"TM/F4XYZ": "F4XYZ",
		"F4XYZ/MM": "F4XYZ",
		"":         "",
	} {
		if got := denyBaseCall(in); got != want {
			t.Errorf("denyBaseCall(%q) = %q, want %q", in, got, want)
		}
	}
}
