package mailruntime

import (
	"strings"
	"testing"

	"productier/apps/backend/internal/store"
)

func TestEncryptDecryptRoundTrip(t *testing.T) {
	service, err := New(store.NewSeededState("test"), nil, "mailruntime-test-secret")
	if err != nil {
		t.Fatalf("New() error = %v", err)
	}

	ciphertext, err := service.encrypt("super-secret-password")
	if err != nil {
		t.Fatalf("encrypt() error = %v", err)
	}

	plain, err := service.decrypt(ciphertext)
	if err != nil {
		t.Fatalf("decrypt() error = %v", err)
	}

	if plain != "super-secret-password" {
		t.Fatalf("decrypt() = %q, want %q", plain, "super-secret-password")
	}
}

func TestBuildOutgoingMessageIncludesHeaders(t *testing.T) {
	messageBytes, err := buildOutgoingMessage(store.MailboxConnection{
		Mailbox: store.Mailbox{
			Email:       "sender@example.com",
			DisplayName: "Sender",
			SMTPHost:    "smtp.example.com",
		},
	}, store.OutgoingMail{
		To: []store.MailAddress{
			{Name: "Recipient", Email: "recipient@example.com"},
		},
		Subject:  "Quarterly Update",
		TextBody: "Plain body",
	})
	if err != nil {
		t.Fatalf("buildOutgoingMessage() error = %v", err)
	}

	message := string(messageBytes)
	for _, fragment := range []string{
		"Subject: Quarterly Update",
		`From: "Sender" <sender@example.com>`,
		`To: "Recipient" <recipient@example.com>`,
		"Plain body",
	} {
		if !strings.Contains(message, fragment) {
			t.Fatalf("built message missing %q\n%s", fragment, message)
		}
	}
}
