package smtpclient

import (
	"bufio"
	"context"
	"net"
	"strings"
	"testing"
	"time"
)

func TestSendUsesConfiguredEnvelopeFrom(t *testing.T) {
	server, client := net.Pipe()
	defer client.Close()

	commands := make(chan string, 32)
	done := make(chan struct{})
	go func() {
		defer close(done)
		defer close(commands)
		defer server.Close()

		r := bufio.NewReader(server)
		w := bufio.NewWriter(server)
		_, _ = w.WriteString("220 test\r\n")
		_ = w.Flush()

		inData := false
		for {
			line, err := r.ReadString('\n')
			if err != nil {
				return
			}
			commands <- line

			switch {
			case inData && line != ".\r\n":
				continue
			case strings.HasPrefix(line, "EHLO "):
				_, _ = w.WriteString("250 test\r\n")
			case strings.HasPrefix(line, "MAIL FROM:"):
				_, _ = w.WriteString("250 ok\r\n")
			case strings.HasPrefix(line, "RCPT TO:"):
				_, _ = w.WriteString("250 ok\r\n")
			case strings.HasPrefix(line, "DATA"):
				inData = true
				_, _ = w.WriteString("354 go ahead\r\n")
			case line == ".\r\n":
				inData = false
				_, _ = w.WriteString("250 queued\r\n")
			case strings.HasPrefix(line, "QUIT"):
				_, _ = w.WriteString("221 bye\r\n")
				_ = w.Flush()
				return
			default:
				continue
			}
			_ = w.Flush()
		}
	}()

	mailer := New(Config{
		Host:         "mail2news.tcpreset.net",
		Port:         25,
		Recipient:    "mail2news@mail2news.tcpreset.net",
		EnvelopeFrom: "n2usenet@virebent.art",
		HELO:         "n2usenet.virebent.art",
		RequireTLS:   false,
		Timeout:      5 * time.Second,
	}, func(ctx context.Context, network, address string) (net.Conn, error) {
		return client, nil
	})

	if err := mailer.Send(context.Background(), Message{
		EnvelopeFrom: "user@example.invalid",
		Raw:          "From: User <user@example.invalid>\r\nTo: mail2news@mail2news.tcpreset.net\r\nSubject: Test\r\n\r\nhello",
	}); err != nil {
		t.Fatalf("Send returned error: %v", err)
	}

	var sawConfiguredFrom bool
	for line := range commands {
		if line == "MAIL FROM:<n2usenet@virebent.art>\r\n" {
			sawConfiguredFrom = true
			break
		}
	}
	<-done

	if !sawConfiguredFrom {
		t.Fatal("configured envelope sender was not used")
	}
}
