package imap

import (
	"strings"
	"testing"
)

func TestParseBody_iso88591Charset(t *testing.T) {
	body := []byte("Vous avez un rendez-vous programm\xe9.\r\nLien de la r\xe9union.")
	var b strings.Builder
	b.WriteString("From: calendar@google.com\r\n")
	b.WriteString("To: user@example.com\r\n")
	b.WriteString("Subject: Invitation\r\n")
	b.WriteString("Content-Type: text/plain; charset=iso-8859-1\r\n")
	b.WriteString("Content-Transfer-Encoding: 8bit\r\n")
	b.WriteString("\r\n")
	b.Write(body)

	text, html := parseBody([]byte(b.String()))
	if html != "" {
		t.Fatalf("html = %q, want empty", html)
	}
	if !strings.Contains(text, "programmé") {
		t.Fatalf("text = %q, want iso-8859-1 accents", text)
	}
	if !strings.Contains(text, "réunion") {
		t.Fatalf("text = %q, want réunion", text)
	}
}

func TestRepairLegacyCharsetString_latin1BytesInString(t *testing.T) {
	// Simulates DB row stored before charset decode (raw Latin-1 bytes in text column).
	raw := string([]byte{0x56, 0x6f, 0x75, 0x73, 0x20, 0x72, 0xe9, 0x75, 0x6e, 0x69, 0x6f, 0x6e})
	repaired := repairLegacyCharsetString(raw)
	if repaired != "Vous réunion" {
		t.Fatalf("repaired = %q", repaired)
	}
}

func TestRepairStoredBodies_legacyLatin1(t *testing.T) {
	raw := string([]byte("programm\xe9"))
	text, _ := RepairStoredBodies(raw, "")
	if text != "programmé" {
		t.Fatalf("text = %q", text)
	}
}
