package mailer_test

import (
	"context"
	"errors"
	"strings"
	"testing"

	"git.fabledsword.com/bvandeusen/minstrel/internal/mailer"
)

func TestFakeSender_RecordsCalls(t *testing.T) {
	f := &mailer.FakeSender{}
	if err := f.Send(context.Background(), "u@example.com", "Subj", "text body", "<p>html body</p>"); err != nil {
		t.Fatalf("Send: %v", err)
	}
	if len(f.Sent) != 1 {
		t.Fatalf("Sent len = %d, want 1", len(f.Sent))
	}
	got := f.LastSent()
	if got.To != "u@example.com" || got.Subject != "Subj" {
		t.Errorf("LastSent = %+v", got)
	}
}

func TestFakeSender_FailNext(t *testing.T) {
	f := &mailer.FakeSender{FailNext: errors.New("simulated")}
	if err := f.Send(context.Background(), "u@example.com", "Subj", "t", "h"); err == nil {
		t.Errorf("Send returned nil, want error")
	}
	// Subsequent call should succeed (FailNext consumed).
	if err := f.Send(context.Background(), "u@example.com", "Subj", "t", "h"); err != nil {
		t.Errorf("second Send: %v", err)
	}
	if len(f.Sent) != 1 {
		t.Errorf("Sent len = %d, want 1 (first call failed, second recorded)", len(f.Sent))
	}
}

func TestRenderResetEmail(t *testing.T) {
	textBody, htmlBody, err := mailer.RenderResetEmail(mailer.ResetEmailVars{
		Username:    "alice",
		ResetURL:    "https://example.com/reset/abc123",
		ExpiryHours: 24,
	})
	if err != nil {
		t.Fatalf("RenderResetEmail: %v", err)
	}
	if !strings.Contains(textBody, "alice") {
		t.Errorf("textBody missing username; got: %s", textBody)
	}
	if !strings.Contains(textBody, "https://example.com/reset/abc123") {
		t.Errorf("textBody missing reset URL; got: %s", textBody)
	}
	if !strings.Contains(textBody, "24") {
		t.Errorf("textBody missing expiry hours; got: %s", textBody)
	}
	if !strings.Contains(htmlBody, "alice") {
		t.Errorf("htmlBody missing username")
	}
	if !strings.Contains(htmlBody, "https://example.com/reset/abc123") {
		t.Errorf("htmlBody missing reset URL")
	}
}
