package mailparser_test

import (
	"os"
	"path/filepath"
	"strings"
	"testing"

	"archivmail/pkg/mailparser"
)

func readFixture(t *testing.T, name string) []byte {
	t.Helper()
	data, err := os.ReadFile(filepath.Join("testdata", name))
	if err != nil {
		t.Fatalf("readFixture %s: %v", name, err)
	}
	return data
}

func TestParseSimple(t *testing.T) {
	raw := readFixture(t, "simple.eml")
	p, err := mailparser.Parse(raw)
	if err != nil {
		t.Fatalf("Parse: %v", err)
	}

	if p.From != "alice@example.com" {
		t.Errorf("From = %q, want alice@example.com", p.From)
	}
	if len(p.To) != 2 {
		t.Errorf("To: got %d recipients, want 2", len(p.To))
	}
	if len(p.CC) != 1 {
		t.Errorf("CC: got %d, want 1", len(p.CC))
	}
	if p.Subject != "Test Invoice Q1-2026" {
		t.Errorf("Subject = %q", p.Subject)
	}
	if p.MessageID != "test-001@example.com" {
		t.Errorf("MessageID = %q", p.MessageID)
	}
	if !strings.Contains(p.TextBody, "invoice") {
		t.Errorf("TextBody missing 'invoice': %q", p.TextBody)
	}
	if p.Date.IsZero() {
		t.Error("Date is zero")
	}
}

func TestParseMultipartWithAttachment(t *testing.T) {
	raw := readFixture(t, "multipart.eml")
	p, err := mailparser.Parse(raw)
	if err != nil {
		t.Fatalf("Parse: %v", err)
	}

	if p.From != "sender@corp.de" {
		t.Errorf("From = %q", p.From)
	}
	if len(p.Attachments) != 1 {
		t.Fatalf("expected 1 attachment, got %d", len(p.Attachments))
	}
	att := p.Attachments[0]
	if att.Filename != "angebot.pdf" {
		t.Errorf("Attachment filename = %q, want angebot.pdf", att.Filename)
	}
	if !strings.Contains(att.ContentType, "pdf") {
		t.Errorf("ContentType = %q, want pdf", att.ContentType)
	}
	if att.Size == 0 {
		t.Error("attachment size is 0")
	}
}

func TestParseRawInline(t *testing.T) {
	raw := []byte("From: test@example.com\r\nTo: dest@example.com\r\nSubject: Hello\r\n\r\nBody text here")
	p, err := mailparser.Parse(raw)
	if err != nil {
		t.Fatalf("Parse: %v", err)
	}
	if p.From != "test@example.com" {
		t.Errorf("From = %q", p.From)
	}
	if len(p.Attachments) != 0 {
		t.Errorf("expected 0 attachments, got %d", len(p.Attachments))
	}
}

func TestParseMissingDate(t *testing.T) {
	raw := []byte("From: test@example.com\r\nSubject: No Date\r\n\r\nNo date header")
	p, err := mailparser.Parse(raw)
	if err != nil {
		t.Fatalf("Parse: %v", err)
	}
	// Should fall back to time.Now(), so should not be zero
	if p.Date.IsZero() {
		t.Error("Date should fall back to now, not zero")
	}
}
