package proxy_test

import (
	"testing"

	"github.com/stretchr/testify/assert"

	"github.com/veylant/ia-gateway/internal/pii"
	"github.com/veylant/ia-gateway/internal/proxy"
)

func TestBuildEntityMap(t *testing.T) {
	entities := []pii.Entity{
		{Pseudonym: "[PII:EMAIL:abc12345]", OriginalValue: "alice@example.com"},
		{Pseudonym: "[PII:PHONE_FR:def67890]", OriginalValue: "0612345678"},
	}
	m := proxy.BuildEntityMap(entities)
	assert.Equal(t, "alice@example.com", m["[PII:EMAIL:abc12345]"])
	assert.Equal(t, "0612345678", m["[PII:PHONE_FR:def67890]"])
}

func TestBuildEntityMap_EmptyPseudonymSkipped(t *testing.T) {
	entities := []pii.Entity{
		{Pseudonym: "", OriginalValue: "ghost"},
	}
	m := proxy.BuildEntityMap(entities)
	assert.Empty(t, m)
}

func TestDepseudonymize_SingleToken(t *testing.T) {
	text := "Contact [PII:EMAIL:abc12345] for info."
	m := map[string]string{"[PII:EMAIL:abc12345]": "alice@example.com"}
	got := proxy.Depseudonymize(text, m)
	assert.Equal(t, "Contact alice@example.com for info.", got)
}

func TestDepseudonymize_MultipleTokens(t *testing.T) {
	text := "[PII:EMAIL:abc12345] and [PII:PHONE_FR:def67890]"
	m := map[string]string{
		"[PII:EMAIL:abc12345]":    "alice@example.com",
		"[PII:PHONE_FR:def67890]": "0612345678",
	}
	got := proxy.Depseudonymize(text, m)
	assert.Contains(t, got, "alice@example.com")
	assert.Contains(t, got, "0612345678")
}

func TestDepseudonymize_UnknownTokenLeftAsIs(t *testing.T) {
	text := "[PII:EMAIL:deadbeef]"
	got := proxy.Depseudonymize(text, map[string]string{})
	assert.Equal(t, "[PII:EMAIL:deadbeef]", got)
}

func TestDepseudonymize_NoTokensNoChange(t *testing.T) {
	text := "Bonjour, tout va bien."
	got := proxy.Depseudonymize(text, map[string]string{"[PII:EMAIL:abc12345]": "x"})
	assert.Equal(t, text, got)
}

func TestDepseudonymize_EmptyMapNoChange(t *testing.T) {
	text := "[PII:EMAIL:abc12345]"
	got := proxy.Depseudonymize(text, nil)
	assert.Equal(t, text, got)
}
