package main

import (
	"strings"
	"testing"
)

// TestBuildAichatPaliadinConfig pins the env-driven wiring used by the
// PALIADIN_BACKEND=aichat path in main(). It guards three things:
//
//  1. Required vars (AICHAT_URL, AICHAT_TOKEN) must be set — otherwise
//     boot fails fast with a clear error message.
//  2. AICHAT_PERSONA defaults to "paliadin" so a misconfigured deploy
//     doesn't silently route to a different persona.
//  3. The JWT secret threads through so per-turn JWT mint is on by
//     default (folded-in t-paliad-156 work).
//
// We can't unit-test the switch{} block in main() directly without
// invoking the rest of boot, so this test exercises the helper that
// branch calls — the same surface a Phase B regression would hit.
func TestBuildAichatPaliadinConfig(t *testing.T) {
	t.Run("rejects empty URL", func(t *testing.T) {
		t.Setenv("AICHAT_URL", "")
		t.Setenv("AICHAT_TOKEN", "tok")
		_, err := buildAichatPaliadinConfig("secret")
		if err == nil || !strings.Contains(err.Error(), "AICHAT_URL") {
			t.Errorf("err = %v; want AICHAT_URL complaint", err)
		}
	})

	t.Run("rejects empty token", func(t *testing.T) {
		t.Setenv("AICHAT_URL", "http://aichat.test")
		t.Setenv("AICHAT_TOKEN", "")
		_, err := buildAichatPaliadinConfig("secret")
		if err == nil || !strings.Contains(err.Error(), "AICHAT_TOKEN") {
			t.Errorf("err = %v; want AICHAT_TOKEN complaint", err)
		}
	})

	t.Run("defaults persona to paliadin", func(t *testing.T) {
		t.Setenv("AICHAT_URL", "http://aichat.test/")
		t.Setenv("AICHAT_TOKEN", "tok")
		t.Setenv("AICHAT_PERSONA", "")
		cfg, err := buildAichatPaliadinConfig("secret")
		if err != nil {
			t.Fatalf("err: %v", err)
		}
		if cfg.Persona != "paliadin" {
			t.Errorf("persona = %q; want paliadin", cfg.Persona)
		}
		if cfg.BaseURL != "http://aichat.test" {
			t.Errorf("base url trailing slash leaked: %q", cfg.BaseURL)
		}
		if string(cfg.JWTSecret) != "secret" {
			t.Errorf("JWT secret not threaded; got %q", string(cfg.JWTSecret))
		}
		if cfg.BearerToken != "tok" {
			t.Errorf("BearerToken = %q; want tok", cfg.BearerToken)
		}
	})

	t.Run("honours AICHAT_PERSONA override", func(t *testing.T) {
		t.Setenv("AICHAT_URL", "http://aichat.test")
		t.Setenv("AICHAT_TOKEN", "tok")
		t.Setenv("AICHAT_PERSONA", "custom-paliadin")
		cfg, err := buildAichatPaliadinConfig("secret")
		if err != nil {
			t.Fatalf("err: %v", err)
		}
		if cfg.Persona != "custom-paliadin" {
			t.Errorf("persona = %q; want custom-paliadin", cfg.Persona)
		}
	})
}

func TestRLSModeLabel(t *testing.T) {
	if got := rlsModeLabel(nil); got != "service-role" {
		t.Errorf("nil → %q; want service-role", got)
	}
	if got := rlsModeLabel([]byte{}); got != "service-role" {
		t.Errorf("empty → %q; want service-role", got)
	}
	if got := rlsModeLabel([]byte("x")); got != "per-user" {
		t.Errorf("non-empty → %q; want per-user", got)
	}
}
